dsh-chief 1.5.0 → 1.7.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 +63 -0
- package/README.en.md +281 -129
- package/README.md +286 -134
- package/api-routes.js +232 -2
- package/board-actions.js +1452 -2005
- package/board-handoff.js +709 -0
- package/board-schema.js +365 -7
- package/chief-approvals.js +6 -2
- package/chief-archives.js +1 -0
- package/chief-commands.js +1884 -3484
- package/chief-compaction.js +1 -0
- package/chief-executor.js +6 -1
- package/chief-models.js +112 -5
- package/chief-network.js +1098 -869
- package/chief-review.js +448 -51
- package/chief-state.js +1996 -2523
- package/chief-view.js +10 -4
- package/client.js +20318 -11591
- package/command-helpers.js +568 -0
- package/command-ops.js +1226 -0
- package/digest.js +29 -4
- package/idle-guard.js +233 -8
- package/index.js +6 -0
- package/locale/en.json +72 -1
- package/locale/zh.json +72 -1
- package/model-tools.js +46 -3
- package/network-harness.js +1047 -0
- package/package.json +13 -5
- package/runtime-hooks.js +316 -14
- package/safety/guard-walls.js +5 -0
- package/safety/invariant-guards.js +126 -6
- package/safety/tool-gate.js +2 -0
- package/state-media.js +173 -0
- package/state-schema.js +1505 -0
- package/subagent-runtime.js +85 -4
package/chief-review.js
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
|
|
7
7
|
import crypto from 'node:crypto'
|
|
8
8
|
import { loadArchiveStore } from './archives.js'
|
|
9
|
-
import { normalizePermissionMode, permissionRank } from './chief-executor.js'
|
|
9
|
+
import { normalizePermissionMode, permissionRank, buildCapabilityScope } from './chief-executor.js'
|
|
10
|
+
import { detectPrematurePromiseText } from './idle-guard.js'
|
|
10
11
|
import {
|
|
11
12
|
CHAT_CAP,
|
|
12
13
|
REVIEW_DELAY_MS,
|
|
@@ -15,6 +16,7 @@ import {
|
|
|
15
16
|
DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
|
|
16
17
|
SUMMARY_MAX_TOKENS,
|
|
17
18
|
archiveTargetForRoot,
|
|
19
|
+
collectChiefVisibleArchives,
|
|
18
20
|
nextId,
|
|
19
21
|
clamp,
|
|
20
22
|
cleanMultiline,
|
|
@@ -34,6 +36,7 @@ import {
|
|
|
34
36
|
beginChiefActiveWork,
|
|
35
37
|
updateChiefActiveWork,
|
|
36
38
|
endChiefActiveWork,
|
|
39
|
+
pushAlertEventToWs,
|
|
37
40
|
} from './chief-state.js'
|
|
38
41
|
import { listChiefModels, callChiefLlm } from './chief-models.js'
|
|
39
42
|
import { listPeerDirectory, deliverCrossMessage } from './chief-network.js'
|
|
@@ -46,7 +49,7 @@ import {
|
|
|
46
49
|
executeHarvestAndCompact,
|
|
47
50
|
maybeRunPreCompaction,
|
|
48
51
|
} from './chief-compaction.js'
|
|
49
|
-
import { applyFactChanges, applyBoardOps } from './chief-commands.js'
|
|
52
|
+
import { applyFactChanges, applyBoardOps, executeChiefArchiveInjectionOp } from './chief-commands.js'
|
|
50
53
|
import { executeBatchSuggestions } from './chief-approvals.js'
|
|
51
54
|
|
|
52
55
|
const TURN_REVIEW_SYSTEM = [
|
|
@@ -65,13 +68,14 @@ const TURN_REVIEW_SYSTEM = [
|
|
|
65
68
|
' - 当 `INTERVENTION_SUPERVISOR` 或 `AUTO_PILOT_SESSION_ONLY` 开启时,你必须严密审查:主/子代理刚刚提出、准备执行、请求用户拍板,或接下来继续推进是否**存在重大不可逆风险,或继续推进必然会撞穿当前生效边界(尤其 🚫 禁止红线)**?',
|
|
66
69
|
' - **重要提示(下列仅是常见举例,绝不限于此!)**:包括但不限于实际花钱/扣费/下单/付费 API 调用、不可逆删除或清空文件/数据/仓库、下载超大文件占用巨额磁盘或流量、关闭/重启服务器或关键宿主服务、对外公开推送/发布不可撤回变更、破坏宿主机隔离边界、以及任何一旦继续推跑就会导致不可逆损失或必然撞穿红线的情形。',
|
|
67
70
|
' - 一旦命中任一上述风险或必然撞边界:**必须立即设 `"hazardStop": { "triggered": true, "category": "...", "title": "简短醒目告警标题", "reason": "用清晰人话说清具体会造成什么不可逆损失或必然撞上哪条边界,以及为何必须立即停下等用户处理" }`,并强制设 `"shouldIntervene": false`、`interventionText: ""`**(严禁再推下一轮!)。',
|
|
68
|
-
'6. `shouldIntervene` & `interventionText`:当开启「主动强介入 (`INTERVENTION_SUPERVISOR`)」且 `hazardStop.triggered === false
|
|
71
|
+
'6. `shouldIntervene` & `interventionText`:当开启「主动强介入 (`INTERVENTION_SUPERVISOR`)」且 `hazardStop.triggered === false` 时,**触发复盘代表主对话刚刚结束了本轮输出、当前已停下进入空闲 (`status=idle`)**!对照「核心目标 + 必做事项 + 最新用户/参谋诉求」逐项核验:只要目标或必做事项尚未真正做完、主对话仅用「重启 XX / 补跑剩余 N 张 / 接下来写脚本 / 继续推进」等口头预告收尾却未真正调用工具落实、或缺少实测验证证据却自称完成,**必须**设 `shouldIntervene: true` 并写出清晰可执行、可直接投递给 `@lead` 继续推进下一回合的 `interventionText` 督导指令;若处于 `strictVerify` 模式但回复无实测输出证据,务必驳回自称完成并要求补跑验证;若开启 `conciseBrief`,督导指令严格限定在 3 条以内要点。仅当核心目标与必做事项均已完成 (`achieved`)、或确认有活跃子代理正在后台运行等待回信时,才设 `shouldIntervene: false`。',
|
|
69
72
|
'7. `suggestions`(最多 1 条,宁缺毋滥):',
|
|
70
73
|
' - `"kind": "bound"`:明显撞墙或发现长期红线/必做规矩时请示注入边界;',
|
|
71
74
|
' - `"kind": "relay"`:发现明确跨对话信息差时的递话建议;',
|
|
72
75
|
' - `"kind": "advice"`:当主模型陷入明显可替代方案、环境坑点或需提醒用户拍板的关键决策时提出一句话建议,可带 `"popup": true|false`(仅关键分叉/阻塞决策设 `true`)。',
|
|
73
76
|
'8. `shouldCompactNow` & `compactReason`:仅当 `SMART_COMPACT_CO_MANAGED`(✦ 智选)启用时评估!此时硬性上下文阈值已退让为辅助,由你与主会话共同把控压缩时机:只要一个完整阶段目标刚刚收口、工作流切换阶段、出现大量重复试错/工具噪音日志、或上下文估算已达 ≥30% 且适合归档脱水时,果断设 `shouldCompactNow: true` 并填写一句话 `compactReason`;仅在刚起步或上下文极轻时保持 `false`。',
|
|
74
77
|
'9. `AUTO_PILOT_SESSION_ONLY`(全自动托管安全边界):当激活标志包含 `AUTO_PILOT_SESSION_ONLY` 时,所有自动决策仅限本对话会话内部!严禁将本会话规律生成 `"pinGlobal": true` 的全局定住边界,严禁跨出本对话去篡改全局档案柜或无关独立窗口;发现跨窗口传递信息时可留待人工审批。',
|
|
78
|
+
'10. `desktopArchivePin`(按需取档上认知桌面):仅当 prompt 列出的「可用但尚未摆上认知桌面的可见档案」中存在当前任务/卡点/排障**正高度直接需要**的一份时,设 `"desktopArchivePin": { "vaultScope": "session|global", "id": "候选id", "title": "候选标题", "reason": "为何需要摆上一线桌面(30字内)" }`;不需要时**必须为 `null`**。严禁编造列表外的 ID 或触碰冷藏库;`AUTO_PILOT_SESSION_ONLY` 时严禁选 `global`。',
|
|
75
79
|
'',
|
|
76
80
|
'输出格式(严格 JSON):',
|
|
77
81
|
'{',
|
|
@@ -88,10 +92,69 @@ const TURN_REVIEW_SYSTEM = [
|
|
|
88
92
|
' "interventionText": "",',
|
|
89
93
|
' "shouldCompactNow": false,',
|
|
90
94
|
' "compactReason": "",',
|
|
91
|
-
' "suggestions": []',
|
|
95
|
+
' "suggestions": [],',
|
|
96
|
+
' "desktopArchivePin": null',
|
|
92
97
|
'}',
|
|
93
98
|
].join('\n')
|
|
94
99
|
|
|
100
|
+
function buildArchiveCandidates(deps, rootId, stateSnapshot, { autoPilot = false } = {}) {
|
|
101
|
+
if (!rootId || rootId === 'global') return []
|
|
102
|
+
try {
|
|
103
|
+
const vis = collectChiefVisibleArchives(deps, rootId, stateSnapshot)
|
|
104
|
+
const out = []
|
|
105
|
+
const seen = new Set()
|
|
106
|
+
const pushItem = (vaultScope, it) => {
|
|
107
|
+
if (!it || !it.id || it.takenOut) return
|
|
108
|
+
if (vaultScope !== 'session' && vaultScope !== 'global') return
|
|
109
|
+
const key = `${vaultScope}:${it.id}`
|
|
110
|
+
if (seen.has(key)) return
|
|
111
|
+
seen.add(key)
|
|
112
|
+
out.push({
|
|
113
|
+
vaultScope,
|
|
114
|
+
id: String(it.id),
|
|
115
|
+
title: String(it.title || it.id),
|
|
116
|
+
folder: String(it.folder || ''),
|
|
117
|
+
summary: String(it.summary || ''),
|
|
118
|
+
hasHook: Boolean(it.hasHook),
|
|
119
|
+
hookCue: String(it.hookCue || ''),
|
|
120
|
+
points: Array.isArray(it.points) ? it.points : [],
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
const sess = Array.isArray(vis && vis.sessionItems) ? vis.sessionItems : []
|
|
124
|
+
for (const it of sess.filter(x => x && !x.takenOut).slice(0, 5)) pushItem('session', it)
|
|
125
|
+
if (!autoPilot) {
|
|
126
|
+
const glob = Array.isArray(vis && vis.globalHookIndex) ? vis.globalHookIndex : []
|
|
127
|
+
for (const it of glob.filter(x => x && !x.takenOut).slice(0, 3)) pushItem('global', it)
|
|
128
|
+
}
|
|
129
|
+
return out.slice(0, 8)
|
|
130
|
+
} catch {
|
|
131
|
+
return []
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function validateDesktopArchivePin(rawPin, candidates, { autoPilot = false, hazardStopped = false } = {}) {
|
|
136
|
+
if (hazardStopped || !rawPin || typeof rawPin !== 'object' || !Array.isArray(candidates) || !candidates.length) return null
|
|
137
|
+
const rawScope = String(rawPin.vaultScope || '').trim()
|
|
138
|
+
if (rawScope === 'precipitated') return null
|
|
139
|
+
if (autoPilot && rawScope && rawScope !== 'session') return null
|
|
140
|
+
const rawId = String(rawPin.id || '').trim()
|
|
141
|
+
const rawTitle = String(rawPin.title || '').trim()
|
|
142
|
+
if (!rawId && !rawTitle) return null
|
|
143
|
+
const matched = candidates.find(c =>
|
|
144
|
+
(!rawScope || c.vaultScope === rawScope)
|
|
145
|
+
&& ((rawId && c.id === rawId) || (!rawId && rawTitle && c.title === rawTitle)),
|
|
146
|
+
)
|
|
147
|
+
if (!matched) return null
|
|
148
|
+
if (autoPilot && matched.vaultScope !== 'session') return null
|
|
149
|
+
const reason = clamp(String(rawPin.reason || '').trim() || '当前推进正高度命中该历史工程档案', 140)
|
|
150
|
+
return {
|
|
151
|
+
vaultScope: matched.vaultScope,
|
|
152
|
+
id: matched.id,
|
|
153
|
+
title: matched.title,
|
|
154
|
+
reason,
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
95
158
|
/** High-precision backup safety net if the turn-review model missed `hazardStop.triggered` despite unmistakable irreversible hazard or boundary collision cues. */
|
|
96
159
|
function detectEmergencyHazardFallback({ parsed, digestText = '', bounds = {}, isInterventionActive = false }) {
|
|
97
160
|
const rawHs = parsed && parsed.hazardStop && typeof parsed.hazardStop === 'object' ? parsed.hazardStop : null
|
|
@@ -146,6 +209,58 @@ function detectEmergencyHazardFallback({ parsed, digestText = '', bounds = {}, i
|
|
|
146
209
|
|
|
147
210
|
const reviewTimers = new Map()
|
|
148
211
|
|
|
212
|
+
const DIRECTIVE_SOURCE_KINDS = new Set([
|
|
213
|
+
'',
|
|
214
|
+
'user',
|
|
215
|
+
'dsh-chief-relay',
|
|
216
|
+
'dsh-chief-execution-request',
|
|
217
|
+
'dsh-chief-auto-continue',
|
|
218
|
+
])
|
|
219
|
+
|
|
220
|
+
const HIGH_RISK_FALLBACK_RE = /(?:花钱|扣费|付款|付费|下单|充值|删库|永久删除|清空目录|格式化|关闭服务器|停服|重启宿主|git\s+push|npm\s+publish|请确认|请选择|需要您|请指示|请拍板)/i
|
|
221
|
+
|
|
222
|
+
function extractMessageTextBlocks(msg) {
|
|
223
|
+
const blocks = Array.isArray(msg && msg.content)
|
|
224
|
+
? msg.content
|
|
225
|
+
: (typeof (msg && msg.content) === 'string' ? [{ type: 'text', text: msg.content }] : [])
|
|
226
|
+
const textParts = []
|
|
227
|
+
const toolHints = []
|
|
228
|
+
for (const b of blocks) {
|
|
229
|
+
if (!b || typeof b !== 'object') continue
|
|
230
|
+
if (b.type === 'text' && typeof b.text === 'string' && b.text.trim()) {
|
|
231
|
+
textParts.push(b.text.trim())
|
|
232
|
+
} else if ((b.type === 'tool_use' || b.type === 'tool-call' || b.type === 'toolCall') && (b.name || b.toolName)) {
|
|
233
|
+
const tName = String(b.name || b.toolName)
|
|
234
|
+
let argHint = ''
|
|
235
|
+
try {
|
|
236
|
+
const rawArgs = b.input || b.arguments || b.args
|
|
237
|
+
const obj = typeof rawArgs === 'string' ? JSON.parse(rawArgs) : rawArgs
|
|
238
|
+
if (obj && typeof obj === 'object') {
|
|
239
|
+
const val = obj.action || obj.command || obj.cmd || obj.path || obj.file_path || obj.agent || obj.title || ''
|
|
240
|
+
if (val) argHint = clamp(String(val), 40)
|
|
241
|
+
}
|
|
242
|
+
} catch {}
|
|
243
|
+
toolHints.push(argHint ? `${tName}(${argHint})` : tName)
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return {
|
|
247
|
+
text: textParts.join('\n').trim(),
|
|
248
|
+
toolHints,
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function resolveTurnTag(turn) {
|
|
253
|
+
if (typeof turn === 'number' && Number.isFinite(turn)) return String(turn)
|
|
254
|
+
if (turn && typeof turn === 'object') {
|
|
255
|
+
if (turn.turn !== undefined) return String(turn.turn)
|
|
256
|
+
if (turn.index !== undefined) return String(turn.index)
|
|
257
|
+
if (turn.id !== undefined) return String(turn.id)
|
|
258
|
+
if (turn.ok) return 'ok'
|
|
259
|
+
if (turn.error) return 'err'
|
|
260
|
+
}
|
|
261
|
+
return 't'
|
|
262
|
+
}
|
|
263
|
+
|
|
149
264
|
function extractLatestTurnDigest(agent, turn) {
|
|
150
265
|
if (!agent || !agent.session) return null
|
|
151
266
|
try {
|
|
@@ -155,48 +270,63 @@ function extractLatestTurnDigest(agent, turn) {
|
|
|
155
270
|
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
|
156
271
|
const um = msgs[i]
|
|
157
272
|
if (!um || um.role !== 'user') continue
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
const uTxt =
|
|
161
|
-
.filter(b => b && b.type === 'text' && typeof b.text === 'string')
|
|
162
|
-
.map(b => b.text)
|
|
163
|
-
.join('\n')
|
|
164
|
-
.trim()
|
|
273
|
+
const srcKind = String((um.source && um.source.kind) || '').trim()
|
|
274
|
+
if (!DIRECTIVE_SOURCE_KINDS.has(srcKind)) continue
|
|
275
|
+
const uTxt = extractMessageTextBlocks(um).text
|
|
165
276
|
if (uTxt && !isInternalCheckpointNoise(uTxt)) {
|
|
166
277
|
latestUserPrompt = clamp(uTxt, 1000)
|
|
167
278
|
break
|
|
168
279
|
}
|
|
169
280
|
}
|
|
170
281
|
|
|
171
|
-
const
|
|
172
|
-
const
|
|
282
|
+
const scanStart = Math.max(0, msgs.length - 24)
|
|
283
|
+
const collected = []
|
|
173
284
|
let hasUser = false
|
|
174
|
-
|
|
285
|
+
let lastAssistantText = ''
|
|
286
|
+
for (let i = msgs.length - 1; i >= scanStart && collected.length < 8; i -= 1) {
|
|
287
|
+
const m = msgs[i]
|
|
175
288
|
if (!m || !m.role) continue
|
|
176
|
-
|
|
177
|
-
const blocks = Array.isArray(m.content) ? m.content : []
|
|
178
|
-
const txt = blocks
|
|
179
|
-
.filter(b => b && b.type === 'text' && typeof b.text === 'string')
|
|
180
|
-
.map(b => b.text)
|
|
181
|
-
.join('\n')
|
|
182
|
-
.trim()
|
|
183
|
-
if (!txt || isInternalCheckpointNoise(txt)) continue
|
|
289
|
+
const srcKind = String((m.source && m.source.kind) || '').trim()
|
|
184
290
|
if (m.role === 'user') {
|
|
185
|
-
|
|
186
|
-
|
|
291
|
+
if (!DIRECTIVE_SOURCE_KINDS.has(srcKind)) continue
|
|
292
|
+
const uTxt = extractMessageTextBlocks(m).text
|
|
293
|
+
if (!uTxt || isInternalCheckpointNoise(uTxt)) continue
|
|
294
|
+
if (!srcKind || srcKind === 'user') {
|
|
295
|
+
hasUser = true
|
|
296
|
+
collected.push('User: ' + clamp(uTxt, 1200))
|
|
297
|
+
} else {
|
|
298
|
+
collected.push('Chief->Lead: ' + clamp(uTxt, 900))
|
|
299
|
+
}
|
|
187
300
|
} else if (m.role === 'assistant') {
|
|
188
|
-
|
|
301
|
+
const { text: aTxt, toolHints } = extractMessageTextBlocks(m)
|
|
302
|
+
const cleanTxt = aTxt && !isInternalCheckpointNoise(aTxt) ? aTxt : ''
|
|
303
|
+
if (!cleanTxt && !toolHints.length) continue
|
|
304
|
+
if (cleanTxt) {
|
|
305
|
+
if (!lastAssistantText) lastAssistantText = cleanTxt
|
|
306
|
+
collected.push('Assistant: ' + clamp(cleanTxt, 900) + (toolHints.length ? ` [Tools: ${toolHints.slice(0, 4).join(' -> ')}]` : ''))
|
|
307
|
+
} else {
|
|
308
|
+
collected.push('Assistant Tools: ' + toolHints.slice(0, 6).join(' -> '))
|
|
309
|
+
}
|
|
189
310
|
}
|
|
190
311
|
}
|
|
191
|
-
|
|
312
|
+
const lines = collected.reverse()
|
|
313
|
+
if (lines.length > 0) {
|
|
314
|
+
const joined = lines.join('\n')
|
|
315
|
+
const lastMsg = msgs[msgs.length - 1]
|
|
316
|
+
const lastMsgId = String((lastMsg && (lastMsg.id || lastMsg.messageId || lastMsg.timestamp)) || 'm').slice(0, 24)
|
|
317
|
+
const tailHash8 = crypto.createHash('sha1').update(joined).digest('hex').slice(0, 8)
|
|
318
|
+
const stamp = `${resolveTurnTag(turn)}:${msgs.length}:${lastMsgId}:${tailHash8}`
|
|
319
|
+
return { text: joined, hasUser, latestUserPrompt, lastAssistantText, msgCount: msgs.length, stamp }
|
|
320
|
+
}
|
|
192
321
|
}
|
|
193
322
|
} catch {}
|
|
194
323
|
return null
|
|
195
324
|
}
|
|
196
325
|
|
|
197
326
|
const lastReviewAtByRoot = new Map()
|
|
327
|
+
const lastFallbackStampByRoot = new Map()
|
|
198
328
|
|
|
199
|
-
export function scheduleChiefTurnReview(deps, { agent, sessionId, turn, abnormalTrigger = '' }) {
|
|
329
|
+
export function scheduleChiefTurnReview(deps, { agent, sessionId, turn, abnormalTrigger = '', delayOverrideMs = null }) {
|
|
200
330
|
const sid = String(sessionId || (agent && agent.id) || '').trim()
|
|
201
331
|
if (!sid) return
|
|
202
332
|
// Never waste tokens reviewing internal mnemon checkpoint / probe subagents
|
|
@@ -211,16 +341,17 @@ export function scheduleChiefTurnReview(deps, { agent, sessionId, turn, abnormal
|
|
|
211
341
|
const wsSnap = state.workspaces && state.workspaces[rootKey] ? state.workspaces[rootKey] : null
|
|
212
342
|
const pendingSmart = Boolean(wsSnap && wsSnap.runtimeGuard && wsSnap.runtimeGuard.pendingSmartCompact)
|
|
213
343
|
const compactChannel = Boolean(tactical.autoCompact || tactical.smartCompact || pendingSmart)
|
|
344
|
+
const interventionChannel = Boolean(tactical.intervention)
|
|
214
345
|
|
|
215
|
-
if (effCfg.stopped || (runMode === 'off' && !compactChannel)) {
|
|
346
|
+
if (effCfg.stopped || (runMode === 'off' && !compactChannel && !interventionChannel)) {
|
|
216
347
|
clearTimeout(reviewTimers.get(rootKey))
|
|
217
348
|
reviewTimers.delete(rootKey)
|
|
218
349
|
return
|
|
219
350
|
}
|
|
220
351
|
|
|
221
|
-
// In PATROL mode: normal turns consume 0 background tokens; wake ONLY on explicit abnormal triggers or
|
|
352
|
+
// In PATROL mode: normal turns consume 0 background tokens; wake ONLY on explicit abnormal triggers, compaction, or intervention
|
|
222
353
|
const hasAbnormal = Boolean(String(abnormalTrigger || '').trim())
|
|
223
|
-
if (runMode === 'patrol' && !hasAbnormal && !compactChannel) {
|
|
354
|
+
if (runMode === 'patrol' && !hasAbnormal && !compactChannel && !interventionChannel) {
|
|
224
355
|
return
|
|
225
356
|
}
|
|
226
357
|
|
|
@@ -228,10 +359,12 @@ export function scheduleChiefTurnReview(deps, { agent, sessionId, turn, abnormal
|
|
|
228
359
|
? deps.boardForSession(deps.boardFileFor(rootKey))
|
|
229
360
|
: null
|
|
230
361
|
const isGoalMode = Boolean(board && board.mode === 'goal')
|
|
231
|
-
const hasHighPriorityChannel = hasAbnormal || isGoalMode || compactChannel ||
|
|
362
|
+
const hasHighPriorityChannel = hasAbnormal || isGoalMode || compactChannel || interventionChannel || tactical.redlineSentinel || tactical.strictVerify
|
|
232
363
|
|
|
233
364
|
clearTimeout(reviewTimers.get(rootKey))
|
|
234
|
-
const delayMs =
|
|
365
|
+
const delayMs = delayOverrideMs !== null && Number.isFinite(Number(delayOverrideMs)) && Number(delayOverrideMs) >= 0
|
|
366
|
+
? Math.max(100, Math.round(Number(delayOverrideMs)))
|
|
367
|
+
: (hasHighPriorityChannel ? 1_200 : REVIEW_DELAY_MS)
|
|
235
368
|
const timer = setTimeout(() => {
|
|
236
369
|
reviewTimers.delete(rootKey)
|
|
237
370
|
runTurnReview(deps, { agent, sessionId: sid, turn, abnormalTrigger }).catch(() => {})
|
|
@@ -253,12 +386,13 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
253
386
|
const wsBefore = ensureWorkspace(stateBefore, rootId)
|
|
254
387
|
const pendingSmart = Boolean(wsBefore.runtimeGuard && wsBefore.runtimeGuard.pendingSmartCompact)
|
|
255
388
|
const compactChannel = Boolean(tactical.autoCompact || tactical.smartCompact || pendingSmart)
|
|
389
|
+
const interventionChannel = Boolean(tactical.intervention)
|
|
256
390
|
const hasAbnormal = Boolean(String(abnormalTrigger || '').trim())
|
|
257
391
|
|
|
258
392
|
if (!force && effCfgBefore.stopped) {
|
|
259
393
|
return { ok: false, skipped: 'chief-stopped' }
|
|
260
394
|
}
|
|
261
|
-
if (!force && runMode === 'off' && !compactChannel) {
|
|
395
|
+
if (!force && runMode === 'off' && !compactChannel && !interventionChannel) {
|
|
262
396
|
return { ok: false, skipped: 'off' }
|
|
263
397
|
}
|
|
264
398
|
const board = deps.boardForSession && deps.boardFileFor
|
|
@@ -266,7 +400,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
266
400
|
: null
|
|
267
401
|
const isGoalMode = Boolean(board && board.mode === 'goal')
|
|
268
402
|
const smartCoManaged = Boolean(tactical.smartCompact)
|
|
269
|
-
const hasHighPriority = hasAbnormal || isGoalMode ||
|
|
403
|
+
const hasHighPriority = hasAbnormal || isGoalMode || interventionChannel || tactical.redlineSentinel || tactical.strictVerify || compactChannel
|
|
270
404
|
|
|
271
405
|
// Always check pre-compaction pipeline first when autoCompact/smartCompact/pendingSmartCompact is active
|
|
272
406
|
if (compactChannel) {
|
|
@@ -278,21 +412,22 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
278
412
|
}
|
|
279
413
|
return { ok: false, error: msg }
|
|
280
414
|
})
|
|
281
|
-
if (preRes && preRes.ok && preRes.smartCompacted) {
|
|
415
|
+
if (preRes && preRes.ok && preRes.smartCompacted && !interventionChannel) {
|
|
282
416
|
return { ok: true, smartCompacted: true, harvestId: preRes.harvestId }
|
|
283
417
|
}
|
|
284
418
|
}
|
|
285
419
|
|
|
286
420
|
// If runMode === 'off' and we only entered for standalone smartCompact/autoCompact pre-check,
|
|
287
|
-
// exit cleanly once autoCompact threshold isn't forcing LLM, except when smartCoManaged
|
|
288
|
-
if (!force && runMode === 'off' && !smartCoManaged) {
|
|
421
|
+
// exit cleanly once autoCompact threshold isn't forcing LLM, except when smartCoManaged or intervention needs evaluation.
|
|
422
|
+
if (!force && runMode === 'off' && !smartCoManaged && !interventionChannel) {
|
|
289
423
|
return { ok: true, onlyCompactionChecked: true }
|
|
290
424
|
}
|
|
291
425
|
|
|
292
|
-
// If ONLY fixed-threshold autoCompact was on (without smartCompact
|
|
426
|
+
// If ONLY fixed-threshold autoCompact was on (without smartCompact, intervention, patrol-abnormal, or managed), exit cleanly
|
|
293
427
|
const needsSupervisorLlm = (runMode === 'managed')
|
|
294
428
|
|| (runMode === 'patrol' && hasAbnormal)
|
|
295
429
|
|| smartCoManaged
|
|
430
|
+
|| interventionChannel
|
|
296
431
|
|| (force && (isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify))
|
|
297
432
|
if (!force && !needsSupervisorLlm && runMode !== 'patrol') {
|
|
298
433
|
return { ok: true, onlyCompactionChecked: true }
|
|
@@ -302,7 +437,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
302
437
|
if (!digest || !digest.text) return { ok: false, skipped: 'no-digest' }
|
|
303
438
|
|
|
304
439
|
const hasWallCue = hasAbnormal || /(?:permission denied|eacces|eperm|forbidden|blocked|not allowed|sandbox|read-only|撞墙|受阻|权限拒绝|越界)/i.test(digest.text)
|
|
305
|
-
if (!force && runMode === 'patrol' && !hasWallCue && !smartCoManaged) {
|
|
440
|
+
if (!force && runMode === 'patrol' && !hasWallCue && !smartCoManaged && !interventionChannel) {
|
|
306
441
|
return { ok: false, skipped: 'patrol-no-abnormal' }
|
|
307
442
|
}
|
|
308
443
|
|
|
@@ -319,7 +454,14 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
319
454
|
const cooldownMs = hasHighPriority
|
|
320
455
|
? (smartCoManaged && !isGoalMode && !tactical.intervention && !hasAbnormal ? 12_000 : 4_000)
|
|
321
456
|
: (runMode === 'patrol' ? (hasWallCue ? 45_000 : SMART_REVIEW_COOLDOWN_MS) : AUTO_REVIEW_COOLDOWN_MS)
|
|
322
|
-
if (!force && now - lastAt < cooldownMs)
|
|
457
|
+
if (!force && now - lastAt < cooldownMs) {
|
|
458
|
+
if (interventionChannel || isGoalMode || hasAbnormal) {
|
|
459
|
+
const waitMs = Math.max(500, cooldownMs - (now - lastAt) + 250)
|
|
460
|
+
scheduleChiefTurnReview(deps, { agent, sessionId: sid, turn, abnormalTrigger, delayOverrideMs: waitMs })
|
|
461
|
+
return { ok: false, skipped: 'cooldown', rescheduled: true, waitMs }
|
|
462
|
+
}
|
|
463
|
+
return { ok: false, skipped: 'cooldown' }
|
|
464
|
+
}
|
|
323
465
|
|
|
324
466
|
// Wait if supervisor/goal/smart-compact is active so turn-stopping settles to idle before evaluating usage
|
|
325
467
|
if ((tactical.intervention || isGoalMode || smartCoManaged) && typeof deps.getAgentStatus === 'function' && !force) {
|
|
@@ -344,7 +486,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
344
486
|
if (smartCoManaged && runMode === 'off') {
|
|
345
487
|
const ratio = liveUsage && liveUsage.contextWindow ? (Number(liveUsage.totalTokens) || 0) / Number(liveUsage.contextWindow) : 0
|
|
346
488
|
const sinceCompact = now - ((wsBefore.runtimeGuard && wsBefore.runtimeGuard.lastCompactedAt) || 0)
|
|
347
|
-
if ((digest.
|
|
489
|
+
if ((digest.msgCount < 4 && ratio < 0.25) || sinceCompact < 20_000) {
|
|
348
490
|
return { ok: false, skipped: 'smart-compact-light' }
|
|
349
491
|
}
|
|
350
492
|
} else if (runMode === 'managed') {
|
|
@@ -388,9 +530,12 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
388
530
|
].filter(Boolean)
|
|
389
531
|
|
|
390
532
|
const smartUsageHint = smartCoManaged
|
|
391
|
-
?
|
|
533
|
+
? `智选共管状态(硬阈值已停用):消息数≈${digest.msgCount}${liveUsage && liveUsage.totalTokens ? `,当前估算上下文 ${liveUsage.totalTokens}/${liveUsage.contextWindow} (${Math.round((liveUsage.totalTokens / liveUsage.contextWindow) * 100)}%)` : ''}`
|
|
392
534
|
: ''
|
|
393
535
|
|
|
536
|
+
const isAutoPilotBefore = Boolean(runMode === 'managed' && !effCfgBefore.stopped)
|
|
537
|
+
const archiveCandidates = buildArchiveCandidates(deps, rootId, loadChiefState(), { autoPilot: isAutoPilotBefore })
|
|
538
|
+
|
|
394
539
|
const prompt = [
|
|
395
540
|
`当前激活监督模式:${activeFlags.join(' | ') || runMode}`,
|
|
396
541
|
...(smartUsageHint ? [smartUsageHint] : []),
|
|
@@ -408,6 +553,11 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
408
553
|
'',
|
|
409
554
|
'已有持久记忆条目:',
|
|
410
555
|
...(numberedFacts.length ? numberedFacts.map((f, i) => `[${i + 1}] (${f.category}) ${f.text}`) : ['(暂无)']),
|
|
556
|
+
...(archiveCandidates.length ? [
|
|
557
|
+
'',
|
|
558
|
+
'可用但尚未摆上认知桌面的可见档案(仅在当前推进高度直接需要时用 desktopArchivePin 调取 1 份,严禁为充数硬拉;冷藏库完全不可见):',
|
|
559
|
+
...archiveCandidates.map(c => `- [${c.vaultScope} | id=${c.id}] 《${clamp(c.title, 44)}》${c.folder ? `(${clamp(c.folder, 20)})` : ''} ${clamp(c.hookCue || c.summary || (c.points && c.points[0] && c.points[0].title) || '', 90)}`),
|
|
560
|
+
] : []),
|
|
411
561
|
'',
|
|
412
562
|
'本轮最新对话片段:',
|
|
413
563
|
digest.text,
|
|
@@ -423,10 +573,56 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
423
573
|
prompt,
|
|
424
574
|
maxTokens: SUMMARY_MAX_TOKENS,
|
|
425
575
|
})
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
576
|
+
const parsed = res && res.ok ? extractJsonObject(res.text) : null
|
|
577
|
+
if (!res.ok || !parsed) {
|
|
578
|
+
const errTag = !res.ok ? (res.error || 'review-llm-failed') : 'non-json-review'
|
|
579
|
+
if (interventionChannel) {
|
|
580
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
581
|
+
deps.appendBoardLog(rootId, `⚠️ 强介入后台复盘异常(${clamp(errTag, 100)}),准备自动重试/兜底检查`, 'chief')
|
|
582
|
+
}
|
|
583
|
+
if (!force && abnormalTrigger !== 'review_retry') {
|
|
584
|
+
scheduleChiefTurnReview(deps, { agent, sessionId: sid, turn, abnormalTrigger: 'review_retry', delayOverrideMs: 5_000 })
|
|
585
|
+
}
|
|
586
|
+
const permCheck = normalizePermissionMode(effCfgBefore.permissionMode, {
|
|
587
|
+
requireAck: true,
|
|
588
|
+
hasChiefRiskAck: hasValidChiefRiskAck(wsBefore),
|
|
589
|
+
})
|
|
590
|
+
const canZeroLlmFallback = permCheck === 'chief'
|
|
591
|
+
&& hasValidChiefRiskAck(wsBefore)
|
|
592
|
+
&& !(identity && identity.isChild)
|
|
593
|
+
&& !HIGH_RISK_FALLBACK_RE.test(digest.lastAssistantText || '')
|
|
594
|
+
const fallbackCue = canZeroLlmFallback ? detectPrematurePromiseText(digest.lastAssistantText || '') : ''
|
|
595
|
+
if (fallbackCue && lastFallbackStampByRoot.get(rootId) !== digest.stamp) {
|
|
596
|
+
lastFallbackStampByRoot.set(rootId, digest.stamp)
|
|
597
|
+
const fbMsg = `【⚡ 参谋长零模型兜底续推】后台复盘模型暂时波动(${clamp(errTag, 60)}),但我检测到你刚才以口头预告下一步(「${fallbackCue}」)直接停在空闲态,且无高危风险提示。请立即调用工具落实该步并验证结果。`
|
|
598
|
+
const fbDeliv = await deliverCrossMessage(deps, {
|
|
599
|
+
fromSession: rootId,
|
|
600
|
+
fromLabel: 'DSH 参谋长 (强介入安全兜底)',
|
|
601
|
+
target: 'lead',
|
|
602
|
+
subject: '口头预告停摆 · 安全兜底推进',
|
|
603
|
+
text: fbMsg,
|
|
604
|
+
mode: 'followup',
|
|
605
|
+
envelopeKind: 'execution_request',
|
|
606
|
+
}).catch(() => null)
|
|
607
|
+
if (fbDeliv && fbDeliv.ok && fbDeliv.deliveredPhysical !== false) {
|
|
608
|
+
mutateChiefState((s) => {
|
|
609
|
+
const ws = ensureWorkspace(s, rootId)
|
|
610
|
+
ws.chat.push({
|
|
611
|
+
id: nextId('chat'),
|
|
612
|
+
role: 'chief',
|
|
613
|
+
kind: 'receipt',
|
|
614
|
+
text: `- 【⚡ 强介入兜底推进】复盘模型暂不可用,已针对口头预告停摆(「${fallbackCue}」)触发安全兜底唤醒 \`@lead\`。`,
|
|
615
|
+
actions: ['⚡ 兜底续推'],
|
|
616
|
+
at: Date.now(),
|
|
617
|
+
})
|
|
618
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
619
|
+
})
|
|
620
|
+
return { ok: true, fallbackIntervened: true, reason: errTag }
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
return !res.ok ? { ok: false, error: res.error } : { ok: false, error: 'non-json-review' }
|
|
625
|
+
}
|
|
430
626
|
|
|
431
627
|
const cfgNow = resolveWorkspaceConfig(loadChiefState(), rootId)
|
|
432
628
|
const wsNowPerm = ensureWorkspace(loadChiefState(), rootId)
|
|
@@ -498,6 +694,19 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
498
694
|
const autoBoundUpdates = []
|
|
499
695
|
let shouldAutoOrganizeSession = false
|
|
500
696
|
|
|
697
|
+
const validatedArchivePin = validateDesktopArchivePin(parsed.desktopArchivePin, archiveCandidates, {
|
|
698
|
+
autoPilot,
|
|
699
|
+
hazardStopped: Boolean(hazardInfo && hazardInfo.triggered),
|
|
700
|
+
})
|
|
701
|
+
let desktopArchiveSuggestionQueued = false
|
|
702
|
+
let desktopArchiveApprovalQueued = false
|
|
703
|
+
let desktopArchivePinned = null
|
|
704
|
+
|
|
705
|
+
const hasRunningChild = realPeers.some(p => p.kind === 'subagent' && p.status === 'running')
|
|
706
|
+
const prematureCue = !(identity && identity.isChild)
|
|
707
|
+
? detectPrematurePromiseText(digest.lastAssistantText || '')
|
|
708
|
+
: ''
|
|
709
|
+
|
|
501
710
|
const isInternalRelayTarget = (targetRaw) => {
|
|
502
711
|
const tq = String(targetRaw || '').trim().replace(/^@/, '')
|
|
503
712
|
if (!tq) return false
|
|
@@ -610,6 +819,42 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
610
819
|
}
|
|
611
820
|
}
|
|
612
821
|
|
|
822
|
+
if (validatedArchivePin && (permNow === 'advisor' || permNow === 'assistant')) {
|
|
823
|
+
const archSug = normalizeSuggestion({
|
|
824
|
+
kind: 'archive_op',
|
|
825
|
+
fromAgent: '🗂️ 档案调度参谋',
|
|
826
|
+
title: `📌 建议将《${clamp(validatedArchivePin.title, 28)}》摆上认知桌面`,
|
|
827
|
+
reason: validatedArchivePin.reason,
|
|
828
|
+
target: 'desktop',
|
|
829
|
+
targetLabel: clamp(validatedArchivePin.title, 28),
|
|
830
|
+
mode: 'silent',
|
|
831
|
+
draftText: `摆上桌面 《${validatedArchivePin.title}》`,
|
|
832
|
+
archiveSpec: {
|
|
833
|
+
op: 'pin_to_desktop',
|
|
834
|
+
vaultScope: validatedArchivePin.vaultScope,
|
|
835
|
+
id: validatedArchivePin.id,
|
|
836
|
+
title: validatedArchivePin.title,
|
|
837
|
+
instruction: validatedArchivePin.reason,
|
|
838
|
+
},
|
|
839
|
+
})
|
|
840
|
+
const dupArch = archSug && ws.suggestions.some(
|
|
841
|
+
existing => existing.status === 'pending'
|
|
842
|
+
&& existing.kind === 'archive_op'
|
|
843
|
+
&& existing.archiveSpec
|
|
844
|
+
&& existing.archiveSpec.id === validatedArchivePin.id
|
|
845
|
+
&& (existing.archiveSpec.vaultScope || 'session') === validatedArchivePin.vaultScope,
|
|
846
|
+
)
|
|
847
|
+
if (archSug && !dupArch) {
|
|
848
|
+
const pending = ws.suggestions.filter(item => item.status === 'pending')
|
|
849
|
+
if (pending.length >= 5) {
|
|
850
|
+
const victim = pending.find(item => item.kind !== 'bound' && item.kind !== 'goal_approval' && item.kind !== 'advice') || pending[0]
|
|
851
|
+
victim.status = 'dismissed'
|
|
852
|
+
}
|
|
853
|
+
ws.suggestions.push(archSug)
|
|
854
|
+
desktopArchiveSuggestionQueued = true
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
613
858
|
// 0) Emergency hazard / boundary-collision gate takes highest priority under Strong Intervention
|
|
614
859
|
if (hazardInfo.triggered && (tactical.intervention || autoPilot)) {
|
|
615
860
|
hazardStopped = true
|
|
@@ -647,15 +892,41 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
647
892
|
})
|
|
648
893
|
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
649
894
|
pushAuditToWs(ws, { mode: permNow, stage: 'safety_guard', decision: 'hazard_stop', operation: '强介入紧急煞车', target: 'lead', reason: hazardAlertCreated.reason, outcome: 'blocked', by: 'chief' })
|
|
895
|
+
pushAlertEventToWs(ws, {
|
|
896
|
+
kind: 'hazard_halt',
|
|
897
|
+
level: 'danger',
|
|
898
|
+
title: hazardAlertCreated.title,
|
|
899
|
+
body: hazardAlertCreated.reason,
|
|
900
|
+
dedupeKey: 'haz:' + hazardAlertCreated.id,
|
|
901
|
+
at: hazardAlertCreated.at || Date.now(),
|
|
902
|
+
})
|
|
650
903
|
} else {
|
|
651
904
|
// Intervention Supervisor follow-up + Circuit Breaker (differentiated across L0 / L1 / L2 / L3)
|
|
652
905
|
const unmetMustDoFallback = unmetMustDo.length > 0
|
|
653
906
|
? '当前尚有以下【必做事项】未确认交付或缺少验证证据,请逐项补齐并交卷:\n' + unmetMustDo.map((u, idx) => `${idx + 1}. ${u}`).join('\n')
|
|
654
907
|
: ''
|
|
908
|
+
const goalMissingFallback = cleanMultiline(parsed.goalMissing || '', 420)
|
|
909
|
+
? `对照锁定核心目标尚有未闭环缺口:${cleanMultiline(parsed.goalMissing, 360)}。请基于当前进展立刻调用工具补齐并提交验证结果。`
|
|
910
|
+
: ''
|
|
911
|
+
const prematureFallback = prematureCue && !hasRunningChild
|
|
912
|
+
? `检测到你刚才以口头预告下一步(「${prematureCue}」)直接结束了回合,但核心目标仍未收口。请立即调用工具把该步实际执行到位并验证输出。`
|
|
913
|
+
: ''
|
|
655
914
|
const candidateIntervention = parsed.interventionText
|
|
656
915
|
|| unmetMustDoFallback
|
|
916
|
+
|| goalMissingFallback
|
|
917
|
+
|| prematureFallback
|
|
657
918
|
|| (parsed.nextActionForLead && (parsed.shouldIntervene || parsed.goalStatus === 'in_progress') ? parsed.nextActionForLead : '')
|
|
658
|
-
|
|
919
|
+
const wantsIntervene = Boolean(
|
|
920
|
+
parsed.shouldIntervene
|
|
921
|
+
|| unmetMustDo.length > 0
|
|
922
|
+
|| (parsed.goalStatus === 'in_progress' && (
|
|
923
|
+
Boolean(parsed.interventionText)
|
|
924
|
+
|| Boolean(parsed.nextActionForLead)
|
|
925
|
+
|| Boolean(parsed.goalMissing)
|
|
926
|
+
|| Boolean(prematureCue && !hasRunningChild)
|
|
927
|
+
))
|
|
928
|
+
)
|
|
929
|
+
if (!isGoalAchieved && tactical.intervention && wantsIntervene && candidateIntervention) {
|
|
659
930
|
const assistantTail = (digest.text.split('Assistant:').pop() || digest.text)
|
|
660
931
|
const sig = crypto
|
|
661
932
|
.createHash('sha1')
|
|
@@ -805,7 +1076,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
805
1076
|
} else {
|
|
806
1077
|
const contextWindow = Math.max(1000, Number(liveUsage && liveUsage.contextWindow) || 128_000)
|
|
807
1078
|
const totalTokens = Number(liveUsage && liveUsage.totalTokens) || 0
|
|
808
|
-
const seq = Math.max(0, Math.round(Number(liveUsage && liveUsage.seq) || digest.
|
|
1079
|
+
const seq = Math.max(0, Math.round(Number(liveUsage && liveUsage.seq) || digest.msgCount || 0))
|
|
809
1080
|
const ratioPct = totalTokens > 0 ? (totalTokens / contextWindow) * 100 : 0
|
|
810
1081
|
updateChiefActiveWork(rootId, reviewWorkId, {
|
|
811
1082
|
tone: 'archive',
|
|
@@ -866,20 +1137,59 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
866
1137
|
})
|
|
867
1138
|
}
|
|
868
1139
|
|
|
1140
|
+
let interventionDeliveredFailed = false
|
|
869
1141
|
if (interventionMessage) {
|
|
870
1142
|
const tags = [
|
|
871
1143
|
tactical.strictVerify ? '严格校验实测' : '',
|
|
872
1144
|
tactical.redlineSentinel ? '红线哨兵巡检' : '',
|
|
873
1145
|
tactical.conciseBrief ? '精炼要点' : '',
|
|
874
1146
|
].filter(Boolean).join(' · ')
|
|
875
|
-
await deliverCrossMessage(deps, {
|
|
1147
|
+
const delivRes = await deliverCrossMessage(deps, {
|
|
876
1148
|
fromSession: rootId,
|
|
877
1149
|
fromLabel: `DSH 参谋长 (接管督导${tags ? '·' + tags : ''})`,
|
|
878
1150
|
target: 'lead',
|
|
879
1151
|
subject: '参谋长自动督导推进',
|
|
880
1152
|
text: interventionMessage,
|
|
881
1153
|
mode: 'followup',
|
|
882
|
-
|
|
1154
|
+
envelopeKind: 'execution_request',
|
|
1155
|
+
}).catch(err => ({ ok: false, deliveredPhysical: false, error: String(err && err.message ? err.message : err) }))
|
|
1156
|
+
const deliveredOk = Boolean(delivRes && delivRes.ok && delivRes.deliveredPhysical !== false)
|
|
1157
|
+
if (deliveredOk) {
|
|
1158
|
+
mutateChiefState((s) => {
|
|
1159
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1160
|
+
const turnIdx = ws.runtimeGuard.interventionTurns || 1
|
|
1161
|
+
ws.chat.push({
|
|
1162
|
+
id: nextId('chat'),
|
|
1163
|
+
role: 'chief',
|
|
1164
|
+
kind: 'receipt',
|
|
1165
|
+
...(res.thinkingEffort ? { thinkingEffort: res.thinkingEffort } : {}),
|
|
1166
|
+
...(res.thinkingEffortMode ? { thinkingEffortMode: res.thinkingEffortMode } : {}),
|
|
1167
|
+
text: `- 【⚡ 强介入督导 · 第 ${turnIdx} 轮】已推动 \`@lead\` 继续执行:${clamp(interventionMessage, 220)}`,
|
|
1168
|
+
actions: [`⚡ 强介入督导 #${turnIdx}`],
|
|
1169
|
+
at: Date.now(),
|
|
1170
|
+
})
|
|
1171
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1172
|
+
})
|
|
1173
|
+
} else {
|
|
1174
|
+
interventionDeliveredFailed = true
|
|
1175
|
+
const failReason = (delivRes && (delivRes.note || delivRes.error)) || '目标会话句柄不可用或离线排队'
|
|
1176
|
+
mutateChiefState((s) => {
|
|
1177
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1178
|
+
ws.runtimeGuard.interventionTurns = Math.max(0, (ws.runtimeGuard.interventionTurns || 0) - 1)
|
|
1179
|
+
ws.chat.push({
|
|
1180
|
+
id: nextId('chat'),
|
|
1181
|
+
role: 'chief',
|
|
1182
|
+
kind: 'receipt',
|
|
1183
|
+
text: `- 【⚠️ 强介入督导未能物理唤醒】未能直接推醒 \`@lead\`(${clamp(failReason, 160)}),本轮未计入强介入次数。`,
|
|
1184
|
+
actions: ['⚠️ 强介入未送达'],
|
|
1185
|
+
at: Date.now(),
|
|
1186
|
+
})
|
|
1187
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1188
|
+
})
|
|
1189
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
1190
|
+
deps.appendBoardLog(rootId, `⚠️ 强介入督导投递未物理唤醒 @lead:${clamp(failReason, 140)}`, 'chief')
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
883
1193
|
}
|
|
884
1194
|
|
|
885
1195
|
if (permRankNow >= 1 && autoBoundUpdates.length > 0 && deps.runAction) {
|
|
@@ -1024,6 +1334,80 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
1024
1334
|
})
|
|
1025
1335
|
}
|
|
1026
1336
|
|
|
1337
|
+
if (validatedArchivePin && !hazardStopped) {
|
|
1338
|
+
if (permNow === 'chief' && hasAckNow) {
|
|
1339
|
+
try {
|
|
1340
|
+
const archRes = await executeChiefArchiveInjectionOp(deps, rootId, {
|
|
1341
|
+
op: 'pin_to_desktop',
|
|
1342
|
+
vaultScope: validatedArchivePin.vaultScope,
|
|
1343
|
+
id: validatedArchivePin.id,
|
|
1344
|
+
title: validatedArchivePin.title,
|
|
1345
|
+
instruction: validatedArchivePin.reason,
|
|
1346
|
+
}, { by: 'chief', input: validatedArchivePin.reason })
|
|
1347
|
+
if (archRes && archRes.ok) {
|
|
1348
|
+
desktopArchivePinned = {
|
|
1349
|
+
ok: true,
|
|
1350
|
+
id: archRes.id,
|
|
1351
|
+
vaultScope: archRes.scope || validatedArchivePin.vaultScope,
|
|
1352
|
+
title: validatedArchivePin.title,
|
|
1353
|
+
actionText: archRes.actionText || '',
|
|
1354
|
+
evicted: Array.isArray(archRes.evicted) ? archRes.evicted : [],
|
|
1355
|
+
}
|
|
1356
|
+
if (typeof deps.appendBoardLog === 'function') {
|
|
1357
|
+
deps.appendBoardLog(rootId, `📌 参谋长主动取档上桌:《${clamp(validatedArchivePin.title, 36)}》`, 'DSH 参谋长')
|
|
1358
|
+
}
|
|
1359
|
+
mutateChiefState((s) => {
|
|
1360
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1361
|
+
pushAuditToWs(ws, {
|
|
1362
|
+
mode: permNow,
|
|
1363
|
+
stage: 'review',
|
|
1364
|
+
rule: 'desktop_archive_pin',
|
|
1365
|
+
decision: 'executed',
|
|
1366
|
+
operation: '推档案上认知桌面',
|
|
1367
|
+
target: clamp(validatedArchivePin.title, 60),
|
|
1368
|
+
reason: validatedArchivePin.reason,
|
|
1369
|
+
outcome: 'ok',
|
|
1370
|
+
by: 'chief',
|
|
1371
|
+
})
|
|
1372
|
+
ws.chat.push({
|
|
1373
|
+
id: nextId('chat'),
|
|
1374
|
+
role: 'chief',
|
|
1375
|
+
kind: 'receipt',
|
|
1376
|
+
...(res.thinkingEffort ? { thinkingEffort: res.thinkingEffort } : {}),
|
|
1377
|
+
...(res.thinkingEffortMode ? { thinkingEffortMode: res.thinkingEffortMode } : {}),
|
|
1378
|
+
text: `- 【📌 参谋长主动取档上桌】已将《${clamp(validatedArchivePin.title, 48)}》(${validatedArchivePin.vaultScope === 'global' ? '全局档案柜' : '本会话档案柜'}) 推入主对话桌面(${validatedArchivePin.reason})。`,
|
|
1379
|
+
actions: [`📌 推档上桌 《${clamp(validatedArchivePin.title, 18)}》`],
|
|
1380
|
+
at: Date.now(),
|
|
1381
|
+
})
|
|
1382
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1383
|
+
})
|
|
1384
|
+
}
|
|
1385
|
+
} catch {}
|
|
1386
|
+
} else if (permNow === 'strategist') {
|
|
1387
|
+
const refTitle = validatedArchivePin.title || validatedArchivePin.id
|
|
1388
|
+
queueChiefApproval(rootId, {
|
|
1389
|
+
category: 'archive_op',
|
|
1390
|
+
operationLabel: '推档案上认知桌面',
|
|
1391
|
+
targetLabel: refTitle,
|
|
1392
|
+
reason: validatedArchivePin.reason,
|
|
1393
|
+
impact: '允许后将该档案置顶到当前会话认知桌面,下一轮自动注入主对话视图',
|
|
1394
|
+
preview: `[${validatedArchivePin.vaultScope}] 《${refTitle}》 (id=${validatedArchivePin.id})`,
|
|
1395
|
+
dedupeKey: `archpin:${rootId}:${validatedArchivePin.vaultScope}:${validatedArchivePin.id}`,
|
|
1396
|
+
kind: 'archive_op',
|
|
1397
|
+
capabilityScope: buildCapabilityScope({ kind: 'archive_op', tool: 'archive_op', target: refTitle }),
|
|
1398
|
+
payload: {
|
|
1399
|
+
op: 'pin_to_desktop',
|
|
1400
|
+
vaultScope: validatedArchivePin.vaultScope,
|
|
1401
|
+
id: validatedArchivePin.id,
|
|
1402
|
+
title: validatedArchivePin.title,
|
|
1403
|
+
instruction: validatedArchivePin.reason,
|
|
1404
|
+
},
|
|
1405
|
+
by: 'chief',
|
|
1406
|
+
})
|
|
1407
|
+
desktopArchiveApprovalQueued = true
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1027
1411
|
let autoPilotStopRes = null
|
|
1028
1412
|
if (autoPilot && !interventionMessage && autoRelays.length === 0 && !circuitTripped) {
|
|
1029
1413
|
autoPilotStopRes = await checkAndStopIdleAutoPilot(deps, rootId, {
|
|
@@ -1044,7 +1428,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
1044
1428
|
goalProposalCreated,
|
|
1045
1429
|
hazardStopped,
|
|
1046
1430
|
...(hazardAlertCreated ? { hazardAlert: hazardAlertCreated } : {}),
|
|
1047
|
-
intervened: Boolean(interventionMessage),
|
|
1431
|
+
intervened: Boolean(interventionMessage && !interventionDeliveredFailed),
|
|
1048
1432
|
queuedInterventionApproval: Boolean(interventionForApproval),
|
|
1049
1433
|
smartCompacted,
|
|
1050
1434
|
circuitTripped,
|
|
@@ -1053,6 +1437,9 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
1053
1437
|
...(res.thinkingEffortMode ? { thinkingEffortMode: res.thinkingEffortMode } : {}),
|
|
1054
1438
|
...(dreamRoamRes ? { dreamRoam: dreamRoamRes } : {}),
|
|
1055
1439
|
...(oneStopReport ? { oneStopReport } : {}),
|
|
1440
|
+
...(desktopArchivePinned ? { desktopArchivePinned } : {}),
|
|
1441
|
+
...(desktopArchiveApprovalQueued ? { desktopArchiveApprovalQueued } : {}),
|
|
1442
|
+
...(desktopArchiveSuggestionQueued ? { desktopArchiveSuggestionQueued } : {}),
|
|
1056
1443
|
...(autoPilotStopRes ? { autoPilotStopped: Boolean(autoPilotStopRes.stopped) } : {}),
|
|
1057
1444
|
}
|
|
1058
1445
|
} finally {
|
|
@@ -1084,6 +1471,9 @@ export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
|
1084
1471
|
if (effBefore.stopped || effBefore.runMode !== 'managed') {
|
|
1085
1472
|
return { ok: true, stopped: false, reason: 'not-managed' }
|
|
1086
1473
|
}
|
|
1474
|
+
if (effBefore.tacticalModes && effBefore.tacticalModes.intervention && !opts.goalAchievedFastStop) {
|
|
1475
|
+
return { ok: true, stopped: false, reason: 'intervention-active' }
|
|
1476
|
+
}
|
|
1087
1477
|
// Condition 5a: 0 pending review timers
|
|
1088
1478
|
if (reviewTimers.has(rootId)) {
|
|
1089
1479
|
return { ok: true, stopped: false, reason: 'review-pending' }
|
|
@@ -1227,6 +1617,13 @@ export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
|
1227
1617
|
at: Date.now(),
|
|
1228
1618
|
})
|
|
1229
1619
|
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1620
|
+
pushAlertEventToWs(ws, {
|
|
1621
|
+
kind: 'managed_auto_sleep',
|
|
1622
|
+
level: 'success',
|
|
1623
|
+
title: '🌙 托管已自动休眠收工',
|
|
1624
|
+
body: '连续闲置达阈值且在途任务、待批弹窗与问询均已清零,已切回「⏸ 关停」。',
|
|
1625
|
+
dedupeKey: `sleep:${rootId}:${Math.floor(Date.now() / 15_000)}`,
|
|
1626
|
+
})
|
|
1230
1627
|
stoppedNow = true
|
|
1231
1628
|
})
|
|
1232
1629
|
|