dsh-chief 1.3.0 → 1.5.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 +84 -12
- package/README.en.md +156 -113
- package/README.md +149 -140
- package/api-routes.js +183 -4
- 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 +131 -5
- package/board-schema.js +1 -1
- package/chief-approvals.js +415 -90
- package/chief-archives.js +191 -29
- package/chief-commands.js +1178 -207
- package/chief-executor.js +279 -555
- package/chief-models.js +158 -28
- package/chief-network.js +157 -8
- package/chief-review.js +240 -67
- package/chief-state.js +855 -109
- package/chief-view.js +38 -20
- package/client.js +5602 -2618
- package/digest.js +18 -9
- package/model-tools.js +92 -6
- package/package.json +41 -25
- package/runtime-hooks.js +221 -12
- package/safety/audit-log.js +95 -0
- package/safety/command-analyzer.js +339 -0
- package/safety/guard-walls.js +993 -0
- package/safety/index.js +78 -0
- package/safety/invariant-guards.js +280 -0
- package/safety/path-guard.js +227 -0
- package/safety/policy-engine.js +387 -0
- package/safety/policy-plugin.js +391 -0
- package/safety/tool-gate.js +278 -0
- package/subagent-runtime.js +266 -3
package/chief-review.js
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
REVIEW_DELAY_MS,
|
|
13
13
|
SMART_REVIEW_COOLDOWN_MS,
|
|
14
14
|
AUTO_REVIEW_COOLDOWN_MS,
|
|
15
|
+
DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
|
|
15
16
|
SUMMARY_MAX_TOKENS,
|
|
16
17
|
archiveTargetForRoot,
|
|
17
18
|
nextId,
|
|
@@ -30,11 +31,14 @@ import {
|
|
|
30
31
|
clusterView,
|
|
31
32
|
isInternalCheckpointNoise,
|
|
32
33
|
extractJsonObject,
|
|
34
|
+
beginChiefActiveWork,
|
|
35
|
+
updateChiefActiveWork,
|
|
36
|
+
endChiefActiveWork,
|
|
33
37
|
} from './chief-state.js'
|
|
34
38
|
import { listChiefModels, callChiefLlm } from './chief-models.js'
|
|
35
39
|
import { listPeerDirectory, deliverCrossMessage } from './chief-network.js'
|
|
36
40
|
import { summarizingLocks, getChiefView, registerIdleAutoPilotHook } from './chief-view.js'
|
|
37
|
-
import {
|
|
41
|
+
import { runManagedDreamRoam } from './chief-archives.js'
|
|
38
42
|
import {
|
|
39
43
|
waitUntilAgentIdle,
|
|
40
44
|
measureAgentSessionTokensFallback,
|
|
@@ -43,6 +47,7 @@ import {
|
|
|
43
47
|
maybeRunPreCompaction,
|
|
44
48
|
} from './chief-compaction.js'
|
|
45
49
|
import { applyFactChanges, applyBoardOps } from './chief-commands.js'
|
|
50
|
+
import { executeBatchSuggestions } from './chief-approvals.js'
|
|
46
51
|
|
|
47
52
|
const TURN_REVIEW_SYSTEM = [
|
|
48
53
|
'你是「DSH 参谋长」(宰相级协同与督导中枢)的后台复盘与督导模块。某个对话刚结束一轮输出。',
|
|
@@ -191,7 +196,7 @@ function extractLatestTurnDigest(agent, turn) {
|
|
|
191
196
|
|
|
192
197
|
const lastReviewAtByRoot = new Map()
|
|
193
198
|
|
|
194
|
-
export function scheduleChiefTurnReview(deps, { agent, sessionId, turn }) {
|
|
199
|
+
export function scheduleChiefTurnReview(deps, { agent, sessionId, turn, abnormalTrigger = '' }) {
|
|
195
200
|
const sid = String(sessionId || (agent && agent.id) || '').trim()
|
|
196
201
|
if (!sid) return
|
|
197
202
|
// Never waste tokens reviewing internal mnemon checkpoint / probe subagents
|
|
@@ -201,35 +206,41 @@ export function scheduleChiefTurnReview(deps, { agent, sessionId, turn }) {
|
|
|
201
206
|
const state = loadChiefState()
|
|
202
207
|
const rootKey = (deps && deps.resolveRootSessionId ? deps.resolveRootSessionId(sid, agent) : '') || sid
|
|
203
208
|
const effCfg = resolveWorkspaceConfig(state, rootKey)
|
|
204
|
-
const
|
|
205
|
-
|
|
209
|
+
const runMode = effCfg.runMode || 'off'
|
|
210
|
+
const tactical = normalizeTacticalModes(effCfg.tacticalModes)
|
|
211
|
+
const wsSnap = state.workspaces && state.workspaces[rootKey] ? state.workspaces[rootKey] : null
|
|
212
|
+
const pendingSmart = Boolean(wsSnap && wsSnap.runtimeGuard && wsSnap.runtimeGuard.pendingSmartCompact)
|
|
213
|
+
const compactChannel = Boolean(tactical.autoCompact || tactical.smartCompact || pendingSmart)
|
|
214
|
+
|
|
215
|
+
if (effCfg.stopped || (runMode === 'off' && !compactChannel)) {
|
|
206
216
|
clearTimeout(reviewTimers.get(rootKey))
|
|
207
217
|
reviewTimers.delete(rootKey)
|
|
208
218
|
return
|
|
209
219
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
const
|
|
220
|
+
|
|
221
|
+
// In PATROL mode: normal turns consume 0 background tokens; wake ONLY on explicit abnormal triggers or compaction checks
|
|
222
|
+
const hasAbnormal = Boolean(String(abnormalTrigger || '').trim())
|
|
223
|
+
if (runMode === 'patrol' && !hasAbnormal && !compactChannel) {
|
|
224
|
+
return
|
|
225
|
+
}
|
|
226
|
+
|
|
213
227
|
const board = deps && deps.boardForSession && deps.boardFileFor
|
|
214
228
|
? deps.boardForSession(deps.boardFileFor(rootKey))
|
|
215
229
|
: null
|
|
216
230
|
const isGoalMode = Boolean(board && board.mode === 'goal')
|
|
217
|
-
const hasHighPriorityChannel =
|
|
218
|
-
|
|
219
|
-
// Default 'manual' mode without tactical/goal active: ZERO background LLM calls!
|
|
220
|
-
if (!hasHighPriorityChannel && (paceMode === 'manual' || effCfg.autoReview === false)) return
|
|
231
|
+
const hasHighPriorityChannel = hasAbnormal || isGoalMode || compactChannel || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify
|
|
221
232
|
|
|
222
233
|
clearTimeout(reviewTimers.get(rootKey))
|
|
223
234
|
const delayMs = hasHighPriorityChannel ? 1_200 : REVIEW_DELAY_MS
|
|
224
235
|
const timer = setTimeout(() => {
|
|
225
236
|
reviewTimers.delete(rootKey)
|
|
226
|
-
runTurnReview(deps, { agent, sessionId: sid, turn }).catch(() => {})
|
|
237
|
+
runTurnReview(deps, { agent, sessionId: sid, turn, abnormalTrigger }).catch(() => {})
|
|
227
238
|
}, delayMs)
|
|
228
239
|
timer.unref?.()
|
|
229
240
|
reviewTimers.set(rootKey, timer)
|
|
230
241
|
}
|
|
231
242
|
|
|
232
|
-
export async function runTurnReview(deps, { agent, sessionId, turn, force = false }) {
|
|
243
|
+
export async function runTurnReview(deps, { agent, sessionId, turn, force = false, abnormalTrigger = '' }) {
|
|
233
244
|
const sid = String(sessionId || (agent && agent.id) || '').trim()
|
|
234
245
|
if (!sid) return { ok: false, skipped: 'no-session' }
|
|
235
246
|
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sid, agent)) || sid
|
|
@@ -237,25 +248,28 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
237
248
|
const stateBefore = loadChiefState()
|
|
238
249
|
const effCfgBefore = resolveWorkspaceConfig(stateBefore, rootId)
|
|
239
250
|
const tactical = normalizeTacticalModes(effCfgBefore.tacticalModes)
|
|
251
|
+
const runMode = effCfgBefore.runMode || 'off'
|
|
240
252
|
const paceMode = effCfgBefore.paceMode || 'manual'
|
|
241
|
-
|
|
253
|
+
const wsBefore = ensureWorkspace(stateBefore, rootId)
|
|
254
|
+
const pendingSmart = Boolean(wsBefore.runtimeGuard && wsBefore.runtimeGuard.pendingSmartCompact)
|
|
255
|
+
const compactChannel = Boolean(tactical.autoCompact || tactical.smartCompact || pendingSmart)
|
|
256
|
+
const hasAbnormal = Boolean(String(abnormalTrigger || '').trim())
|
|
257
|
+
|
|
258
|
+
if (!force && effCfgBefore.stopped) {
|
|
242
259
|
return { ok: false, skipped: 'chief-stopped' }
|
|
243
260
|
}
|
|
244
|
-
|
|
261
|
+
if (!force && runMode === 'off' && !compactChannel) {
|
|
262
|
+
return { ok: false, skipped: 'off' }
|
|
263
|
+
}
|
|
245
264
|
const board = deps.boardForSession && deps.boardFileFor
|
|
246
265
|
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
247
266
|
: null
|
|
248
267
|
const isGoalMode = Boolean(board && board.mode === 'goal')
|
|
249
|
-
const pendingSmart = Boolean(wsBefore.runtimeGuard && wsBefore.runtimeGuard.pendingSmartCompact)
|
|
250
268
|
const smartCoManaged = Boolean(tactical.smartCompact)
|
|
251
|
-
const hasHighPriority = isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify ||
|
|
252
|
-
|
|
253
|
-
if (!force && !hasHighPriority && paceMode === 'manual') {
|
|
254
|
-
return { ok: false, skipped: 'manual' }
|
|
255
|
-
}
|
|
269
|
+
const hasHighPriority = hasAbnormal || isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify || compactChannel
|
|
256
270
|
|
|
257
271
|
// Always check pre-compaction pipeline first when autoCompact/smartCompact/pendingSmartCompact is active
|
|
258
|
-
if (
|
|
272
|
+
if (compactChannel) {
|
|
259
273
|
const preRes = await maybeRunPreCompaction(deps, { agent, sessionId: sid, rootId, bypassIdleWait: Boolean(force) })
|
|
260
274
|
.catch((err) => {
|
|
261
275
|
const msg = (err && err.message) || String(err || 'pre-compact-error')
|
|
@@ -269,13 +283,29 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
269
283
|
}
|
|
270
284
|
}
|
|
271
285
|
|
|
272
|
-
// If
|
|
273
|
-
|
|
274
|
-
if (!force &&
|
|
286
|
+
// 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 needs its idle evaluation.
|
|
288
|
+
if (!force && runMode === 'off' && !smartCoManaged) {
|
|
289
|
+
return { ok: true, onlyCompactionChecked: true }
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// If ONLY fixed-threshold autoCompact was on (without smartCompact or patrol-abnormal or managed), exit cleanly
|
|
293
|
+
const needsSupervisorLlm = (runMode === 'managed')
|
|
294
|
+
|| (runMode === 'patrol' && hasAbnormal)
|
|
295
|
+
|| smartCoManaged
|
|
296
|
+
|| (force && (isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify))
|
|
297
|
+
if (!force && !needsSupervisorLlm && runMode !== 'patrol') {
|
|
298
|
+
return { ok: true, onlyCompactionChecked: true }
|
|
299
|
+
}
|
|
275
300
|
|
|
276
301
|
const digest = extractLatestTurnDigest(agent, turn)
|
|
277
302
|
if (!digest || !digest.text) return { ok: false, skipped: 'no-digest' }
|
|
278
303
|
|
|
304
|
+
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) {
|
|
306
|
+
return { ok: false, skipped: 'patrol-no-abnormal' }
|
|
307
|
+
}
|
|
308
|
+
|
|
279
309
|
const cursorKey = `${sid}`
|
|
280
310
|
if (!force && wsBefore.reviewCursors[cursorKey] === digest.stamp) {
|
|
281
311
|
return { ok: false, skipped: 'same-stamp' }
|
|
@@ -284,12 +314,11 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
284
314
|
const identity = deps.resolveAgentIdentity ? deps.resolveAgentIdentity(deps.runtime, sid, agent) : null
|
|
285
315
|
if (identity && /^mnemon-(?:review|run)/i.test(String(identity.self || ''))) return { ok: false, skipped: 'mnemon' }
|
|
286
316
|
|
|
287
|
-
const hasWallCue = /(?:permission denied|eacces|eperm|forbidden|blocked|not allowed|sandbox|read-only|撞墙|受阻|权限拒绝|越界)/i.test(digest.text)
|
|
288
317
|
const now = Date.now()
|
|
289
318
|
const lastAt = Number(lastReviewAtByRoot.get(rootId) || 0)
|
|
290
319
|
const cooldownMs = hasHighPriority
|
|
291
|
-
? (smartCoManaged && !isGoalMode && !tactical.intervention ? 12_000 : 4_000)
|
|
292
|
-
: (
|
|
320
|
+
? (smartCoManaged && !isGoalMode && !tactical.intervention && !hasAbnormal ? 12_000 : 4_000)
|
|
321
|
+
: (runMode === 'patrol' ? (hasWallCue ? 45_000 : SMART_REVIEW_COOLDOWN_MS) : AUTO_REVIEW_COOLDOWN_MS)
|
|
293
322
|
if (!force && now - lastAt < cooldownMs) return { ok: false, skipped: 'cooldown' }
|
|
294
323
|
|
|
295
324
|
// Wait if supervisor/goal/smart-compact is active so turn-stopping settles to idle before evaluating usage
|
|
@@ -311,17 +340,14 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
311
340
|
|
|
312
341
|
// In 'smart' background mode (without supervisor/goal), gate LLM call on wall cue or multi-agent human turn;
|
|
313
342
|
// when ONLY smartCoManaged is enabled in manual pace, evaluate only after enough turns or context pressure.
|
|
314
|
-
if (!force && !isGoalMode && !tactical.intervention && !tactical.redlineSentinel && !tactical.strictVerify) {
|
|
315
|
-
if (smartCoManaged &&
|
|
343
|
+
if (!force && !isGoalMode && !tactical.intervention && !tactical.redlineSentinel && !tactical.strictVerify && !hasAbnormal) {
|
|
344
|
+
if (smartCoManaged && runMode === 'off') {
|
|
316
345
|
const ratio = liveUsage && liveUsage.contextWindow ? (Number(liveUsage.totalTokens) || 0) / Number(liveUsage.contextWindow) : 0
|
|
317
346
|
const sinceCompact = now - ((wsBefore.runtimeGuard && wsBefore.runtimeGuard.lastCompactedAt) || 0)
|
|
318
347
|
if ((digest.stamp < 4 && ratio < 0.25) || sinceCompact < 20_000) {
|
|
319
348
|
return { ok: false, skipped: 'smart-compact-light' }
|
|
320
349
|
}
|
|
321
|
-
} else {
|
|
322
|
-
if (paceMode === 'smart' && !hasWallCue && !(digest.hasUser && realPeers.length > 1)) {
|
|
323
|
-
return { ok: false, skipped: 'smart-quiet' }
|
|
324
|
-
}
|
|
350
|
+
} else if (runMode === 'managed') {
|
|
325
351
|
if (!digest.hasUser && realPeers.length <= 1 && !hasWallCue) return { ok: false, skipped: 'single-quiet' }
|
|
326
352
|
}
|
|
327
353
|
}
|
|
@@ -332,6 +358,15 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
332
358
|
}
|
|
333
359
|
|
|
334
360
|
lastReviewAtByRoot.set(rootId, now)
|
|
361
|
+
const isAutoPilotActiveNow = Boolean(runMode === 'managed' && !effCfgBefore.stopped)
|
|
362
|
+
const reviewWorkId = beginChiefActiveWork(rootId, {
|
|
363
|
+
tone: 'neon',
|
|
364
|
+
tab: '',
|
|
365
|
+
label: runMode === 'patrol'
|
|
366
|
+
? '参谋长正在巡检异常与诊断边界中...'
|
|
367
|
+
: (isAutoPilotActiveNow ? '参谋长正在托管督导巡检中...' : '参谋长正在后台复盘研判中...'),
|
|
368
|
+
})
|
|
369
|
+
try {
|
|
335
370
|
const speaker = identity && identity.isChild ? `子代理 @${identity.self}` : '主对话 (@lead)'
|
|
336
371
|
const view = clusterView(stateBefore, rootId)
|
|
337
372
|
const numberedFacts = view.facts.slice()
|
|
@@ -348,7 +383,8 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
348
383
|
tactical.strictVerify ? 'STRICT_VERIFY' : '',
|
|
349
384
|
tactical.redlineSentinel ? 'REDLINE_SENTINEL' : '',
|
|
350
385
|
tactical.conciseBrief ? 'CONCISE_BRIEF_3_BULLETS' : '',
|
|
351
|
-
Boolean(
|
|
386
|
+
Boolean(runMode === 'managed' && !effCfgBefore.stopped) ? 'AUTO_PILOT_SESSION_ONLY' : '',
|
|
387
|
+
hasAbnormal ? `ABNORMAL_PATROL_TRIGGER(${abnormalTrigger})` : '',
|
|
352
388
|
].filter(Boolean)
|
|
353
389
|
|
|
354
390
|
const smartUsageHint = smartCoManaged
|
|
@@ -356,7 +392,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
356
392
|
: ''
|
|
357
393
|
|
|
358
394
|
const prompt = [
|
|
359
|
-
`当前激活监督模式:${activeFlags.join(' | ') ||
|
|
395
|
+
`当前激活监督模式:${activeFlags.join(' | ') || runMode}`,
|
|
360
396
|
...(smartUsageHint ? [smartUsageHint] : []),
|
|
361
397
|
`工作区总目标 (Objective):${(board && board.objective) || '(暂未开启 /goal 固定目标 — 请对照下方最新用户原始诉求核验完成度)'}`,
|
|
362
398
|
`最新用户原始诉求:${digest.latestUserPrompt || '(见下方对话片段)'}`,
|
|
@@ -377,8 +413,12 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
377
413
|
digest.text,
|
|
378
414
|
].join('\n')
|
|
379
415
|
|
|
416
|
+
const reviewReasonKind = hasAbnormal
|
|
417
|
+
? 'wall_blocked'
|
|
418
|
+
: (tactical.intervention ? 'strong_intervention' : 'turn_review')
|
|
380
419
|
const res = await callChiefLlm(deps, {
|
|
381
420
|
sessionId: rootId,
|
|
421
|
+
reasonKind: reviewReasonKind,
|
|
382
422
|
system: TURN_REVIEW_SYSTEM,
|
|
383
423
|
prompt,
|
|
384
424
|
maxTokens: SUMMARY_MAX_TOKENS,
|
|
@@ -393,7 +433,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
393
433
|
const hasAckNow = hasValidChiefRiskAck(wsNowPerm)
|
|
394
434
|
const permNow = normalizePermissionMode(cfgNow.permissionMode, { requireAck: true, hasChiefRiskAck: hasAckNow })
|
|
395
435
|
const permRankNow = permissionRank(permNow)
|
|
396
|
-
const autoPilot = Boolean(cfgNow.
|
|
436
|
+
const autoPilot = Boolean(cfgNow.runMode === 'managed' && !cfgNow.stopped)
|
|
397
437
|
const rawSuggestions = (Array.isArray(parsed.suggestions) ? parsed.suggestions : [])
|
|
398
438
|
.map(raw => normalizeSuggestion({ ...raw, fromAgent: raw?.fromAgent || speaker }))
|
|
399
439
|
.filter(Boolean)
|
|
@@ -406,7 +446,10 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
406
446
|
parsedBoardOps.unshift({ op: 'plan.resetForGoal' })
|
|
407
447
|
}
|
|
408
448
|
const executedOps = permRankNow >= 1 && parsedBoardOps.length > 0 && deps.runAction
|
|
409
|
-
?
|
|
449
|
+
? (() => {
|
|
450
|
+
updateChiefActiveWork(rootId, reviewWorkId, { tone: 'tasks', tab: 'tasks', label: '参谋长正在自动同步看板与计划中...' })
|
|
451
|
+
return applyBoardOps(deps, rootId, parsedBoardOps, { forceSessionOnly: autoPilot })
|
|
452
|
+
})()
|
|
410
453
|
: []
|
|
411
454
|
|
|
412
455
|
const unmetMustDo = Array.isArray(parsed.unmetMustDo)
|
|
@@ -517,8 +560,9 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
517
560
|
}
|
|
518
561
|
}
|
|
519
562
|
|
|
563
|
+
const useOneStopRunnerNow = Boolean(permNow === 'chief' && hasAckNow && tactical.intervention)
|
|
520
564
|
for (const sug of rawSuggestions) {
|
|
521
|
-
if (sug.kind === 'bound') {
|
|
565
|
+
if (!useOneStopRunnerNow && sug.kind === 'bound') {
|
|
522
566
|
const colList = Array.isArray(bounds[sug.boundField]) ? bounds[sug.boundField] : []
|
|
523
567
|
if (colList.some(x => String(x).trim() === sug.draftText)) continue
|
|
524
568
|
if (autoPilot && sug.draftText) {
|
|
@@ -528,7 +572,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
528
572
|
continue
|
|
529
573
|
}
|
|
530
574
|
}
|
|
531
|
-
if (autoPilot && sug.kind === 'relay' && sug.draftText && isInternalRelayTarget(sug.target)) {
|
|
575
|
+
if (!useOneStopRunnerNow && autoPilot && sug.kind === 'relay' && sug.draftText && isInternalRelayTarget(sug.target)) {
|
|
532
576
|
if (permNow === 'chief' && hasAckNow) {
|
|
533
577
|
sug.status = 'applied'
|
|
534
578
|
autoRelays.push(sug)
|
|
@@ -558,9 +602,9 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
558
602
|
}
|
|
559
603
|
}
|
|
560
604
|
|
|
561
|
-
if (autoPilot && rootId && rootId !== 'global') {
|
|
605
|
+
if (autoPilot && permRankNow >= 1 && rootId && rootId !== 'global') {
|
|
562
606
|
const lastOrgAt = Number(ws.runtimeGuard.lastAutoArchiveOrgAt || 0)
|
|
563
|
-
if (!lastOrgAt || Date.now() - lastOrgAt >
|
|
607
|
+
if (!lastOrgAt || Date.now() - lastOrgAt > 60_000) {
|
|
564
608
|
shouldAutoOrganizeSession = true
|
|
565
609
|
}
|
|
566
610
|
}
|
|
@@ -763,6 +807,11 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
763
807
|
const totalTokens = Number(liveUsage && liveUsage.totalTokens) || 0
|
|
764
808
|
const seq = Math.max(0, Math.round(Number(liveUsage && liveUsage.seq) || digest.stamp || 0))
|
|
765
809
|
const ratioPct = totalTokens > 0 ? (totalTokens / contextWindow) * 100 : 0
|
|
810
|
+
updateChiefActiveWork(rootId, reviewWorkId, {
|
|
811
|
+
tone: 'archive',
|
|
812
|
+
tab: 'archive',
|
|
813
|
+
label: '参谋长正在自动抢救归档与压缩中...',
|
|
814
|
+
})
|
|
766
815
|
const cRes = await executeHarvestAndCompact(deps, {
|
|
767
816
|
sid,
|
|
768
817
|
rootId,
|
|
@@ -834,6 +883,12 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
834
883
|
}
|
|
835
884
|
|
|
836
885
|
if (permRankNow >= 1 && autoBoundUpdates.length > 0 && deps.runAction) {
|
|
886
|
+
updateChiefActiveWork(rootId, reviewWorkId, {
|
|
887
|
+
tone: 'bounds',
|
|
888
|
+
tab: 'boundaries',
|
|
889
|
+
boundSubTab: 'rules',
|
|
890
|
+
label: '参谋长正在自动维护本局边界中...',
|
|
891
|
+
})
|
|
837
892
|
for (const b of autoBoundUpdates) {
|
|
838
893
|
deps.runAction({
|
|
839
894
|
action: 'bounds.add',
|
|
@@ -847,24 +902,91 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
847
902
|
}
|
|
848
903
|
}
|
|
849
904
|
|
|
850
|
-
|
|
905
|
+
let dreamRoamRes = null
|
|
906
|
+
if (autoPilot && permRankNow >= 1 && !hazardStopped && rootId && rootId !== 'global') {
|
|
851
907
|
try {
|
|
852
908
|
const sessOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'session' })
|
|
909
|
+
const globOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'global' })
|
|
853
910
|
const stSess = loadArchiveStore(sessOpt)
|
|
854
|
-
const
|
|
855
|
-
|
|
856
|
-
).length
|
|
857
|
-
|
|
911
|
+
const stGlob = loadArchiveStore(globOpt)
|
|
912
|
+
const hasWatch = Array.isArray(stSess.recentlyUnpinnedWatch) && stSess.recentlyUnpinnedWatch.length > 0
|
|
913
|
+
const hasUnhookedSess = (stSess.items || []).some(it => !it.hasHook || it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1)
|
|
914
|
+
const hasUnhookedGlob = (stGlob.items || []).some(it => !it.hasHook || it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1)
|
|
915
|
+
if (hasWatch || ((shouldAutoOrganizeSession || force) && (hasUnhookedSess || hasUnhookedGlob))) {
|
|
916
|
+
updateChiefActiveWork(rootId, reviewWorkId, {
|
|
917
|
+
tone: 'dream',
|
|
918
|
+
tab: 'archive',
|
|
919
|
+
label: '🌙 参谋长正在梦境漫游 · 轻拢卷宗与织就钩子中...',
|
|
920
|
+
})
|
|
858
921
|
mutateChiefState((s) => {
|
|
859
922
|
const ws = ensureWorkspace(s, rootId)
|
|
860
923
|
ws.runtimeGuard.lastAutoArchiveOrgAt = Date.now()
|
|
861
924
|
})
|
|
862
|
-
await
|
|
925
|
+
dreamRoamRes = await runManagedDreamRoam(deps, { sessionId: rootId }).catch(() => null)
|
|
926
|
+
}
|
|
927
|
+
} catch {}
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
// L3 Chief + Strong Intervention: One-Stop Task Runner sweeping safe pending suggestions
|
|
931
|
+
// (excludes guard_wall, goal_approval, pinGlobal global bounds, and superseded L1 fallback advice when live intervention ran)
|
|
932
|
+
let oneStopReport = null
|
|
933
|
+
if (permNow === 'chief' && hasAckNow && tactical.intervention && !hazardStopped) {
|
|
934
|
+
try {
|
|
935
|
+
const wsLatest = ensureWorkspace(loadChiefState(), rootId)
|
|
936
|
+
const safePending = (wsLatest.suggestions || []).filter(s =>
|
|
937
|
+
s
|
|
938
|
+
&& s.status === 'pending'
|
|
939
|
+
&& s.kind !== 'guard_wall'
|
|
940
|
+
&& s.kind !== 'wall_removal'
|
|
941
|
+
&& s.kind !== 'goal_approval'
|
|
942
|
+
&& !(s.kind === 'bound' && s.pinGlobal)
|
|
943
|
+
&& !(interventionMessage && s.title === 'L1 强介入建议(等待拍板,未自动递给主对话)'),
|
|
944
|
+
)
|
|
945
|
+
if (safePending.length > 0) {
|
|
946
|
+
updateChiefActiveWork(rootId, reviewWorkId, {
|
|
947
|
+
tone: 'neon',
|
|
948
|
+
tab: 'chief',
|
|
949
|
+
label: '🏁 参谋长正在一站式推进建议清单中...',
|
|
950
|
+
})
|
|
951
|
+
const batchOut = await executeBatchSuggestions(deps, {
|
|
863
952
|
sessionId: rootId,
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
953
|
+
ids: safePending.map(s => s.id),
|
|
954
|
+
includeGoalApproval: false,
|
|
955
|
+
skipGuardWalls: true,
|
|
956
|
+
skipGlobalBounds: true,
|
|
957
|
+
byAutoRunner: true,
|
|
958
|
+
skipChatReceipt: true,
|
|
959
|
+
})
|
|
960
|
+
if (batchOut && (batchOut.executedCount > 0 || batchOut.blockedCount > 0 || batchOut.failedCount > 0)) {
|
|
961
|
+
oneStopReport = {
|
|
962
|
+
executedCount: batchOut.executedCount,
|
|
963
|
+
blockedCount: batchOut.blockedCount,
|
|
964
|
+
failedCount: batchOut.failedCount,
|
|
965
|
+
skippedGoalCount: batchOut.skippedGoalCount,
|
|
966
|
+
summaries: batchOut.summaries || [],
|
|
967
|
+
}
|
|
968
|
+
mutateChiefState((s) => {
|
|
969
|
+
const ws = ensureWorkspace(s, rootId)
|
|
970
|
+
ws.chat.push({
|
|
971
|
+
id: nextId('chat'),
|
|
972
|
+
role: 'chief',
|
|
973
|
+
kind: 'receipt',
|
|
974
|
+
isOneStopReport: true,
|
|
975
|
+
...(res.thinkingEffort ? { thinkingEffort: res.thinkingEffort } : {}),
|
|
976
|
+
...(res.thinkingEffortMode ? { thinkingEffortMode: res.thinkingEffortMode } : {}),
|
|
977
|
+
text: [
|
|
978
|
+
`- 【🏁 一站式战报回执】L3 强介入已顺序推进 ${batchOut.executedCount} 项安全建议${batchOut.blockedCount ? ` · 安全护栏拦禁 ${batchOut.blockedCount} 项` : ''}${batchOut.skippedGoalCount ? ` · 保留高危/结项/全局项 ${batchOut.skippedGoalCount} 项待您亲裁` : ''}`,
|
|
979
|
+
...(batchOut.summaries || []).map(line => ` ${line}`),
|
|
980
|
+
].join('\n'),
|
|
981
|
+
actions: [
|
|
982
|
+
`🏁 一站式执行 ×${batchOut.executedCount}`,
|
|
983
|
+
...(batchOut.blockedCount ? [`🛡️ 红线拦截 ×${batchOut.blockedCount}`] : []),
|
|
984
|
+
],
|
|
985
|
+
at: Date.now(),
|
|
986
|
+
})
|
|
987
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
988
|
+
})
|
|
989
|
+
}
|
|
868
990
|
}
|
|
869
991
|
} catch {}
|
|
870
992
|
}
|
|
@@ -906,6 +1028,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
906
1028
|
if (autoPilot && !interventionMessage && autoRelays.length === 0 && !circuitTripped) {
|
|
907
1029
|
autoPilotStopRes = await checkAndStopIdleAutoPilot(deps, rootId, {
|
|
908
1030
|
allowStartupGrace: false,
|
|
1031
|
+
goalAchievedFastStop: Boolean(isGoalAchieved),
|
|
909
1032
|
directory,
|
|
910
1033
|
fromViewCheck: false,
|
|
911
1034
|
}).catch(() => null)
|
|
@@ -926,15 +1049,25 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
926
1049
|
smartCompacted,
|
|
927
1050
|
circuitTripped,
|
|
928
1051
|
circuitReason,
|
|
1052
|
+
...(res.thinkingEffort ? { thinkingEffort: res.thinkingEffort } : {}),
|
|
1053
|
+
...(res.thinkingEffortMode ? { thinkingEffortMode: res.thinkingEffortMode } : {}),
|
|
1054
|
+
...(dreamRoamRes ? { dreamRoam: dreamRoamRes } : {}),
|
|
1055
|
+
...(oneStopReport ? { oneStopReport } : {}),
|
|
929
1056
|
...(autoPilotStopRes ? { autoPilotStopped: Boolean(autoPilotStopRes.stopped) } : {}),
|
|
930
1057
|
}
|
|
1058
|
+
} finally {
|
|
1059
|
+
endChiefActiveWork(rootId, reviewWorkId)
|
|
1060
|
+
}
|
|
931
1061
|
}
|
|
932
1062
|
|
|
933
1063
|
/**
|
|
934
|
-
*
|
|
935
|
-
*
|
|
936
|
-
*
|
|
937
|
-
*
|
|
1064
|
+
* 5-Condition Idle Auto-Sleep Guard for Managed mode (`runMode === 'managed'`):
|
|
1065
|
+
* Auto-stands down `managed -> off` ONLY when ALL 5 conditions hold:
|
|
1066
|
+
* (1) Idle timeout elapsed (or goal-achieved fast stand-down) AND 0 running session agents;
|
|
1067
|
+
* (2) 0 `doing` tasks on board;
|
|
1068
|
+
* (3) 0 pending approvals / elevations;
|
|
1069
|
+
* (4) 0 pending/delivered open inquiries;
|
|
1070
|
+
* (5) 0 pending review timers AND empty `recentlyUnpinnedWatch` queue.
|
|
938
1071
|
*/
|
|
939
1072
|
export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
940
1073
|
const sidRaw = String(sessionId || '').trim()
|
|
@@ -948,12 +1081,39 @@ export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
|
948
1081
|
const stBefore = loadChiefState()
|
|
949
1082
|
const effBefore = resolveWorkspaceConfig(stBefore, rootId)
|
|
950
1083
|
const wsBefore = ensureWorkspace(stBefore, rootId)
|
|
951
|
-
if (effBefore.stopped || effBefore.
|
|
952
|
-
return { ok: true, stopped: false, reason: 'not-
|
|
1084
|
+
if (effBefore.stopped || effBefore.runMode !== 'managed') {
|
|
1085
|
+
return { ok: true, stopped: false, reason: 'not-managed' }
|
|
953
1086
|
}
|
|
1087
|
+
// Condition 5a: 0 pending review timers
|
|
954
1088
|
if (reviewTimers.has(rootId)) {
|
|
955
1089
|
return { ok: true, stopped: false, reason: 'review-pending' }
|
|
956
1090
|
}
|
|
1091
|
+
// Condition 3: 0 pending approvals / elevations
|
|
1092
|
+
const hasPendingApr = Array.isArray(wsBefore.pendingApprovals) && wsBefore.pendingApprovals.some(a => a && a.status === 'pending')
|
|
1093
|
+
if (hasPendingApr || wsBefore.pendingElevation) {
|
|
1094
|
+
return { ok: true, stopped: false, reason: 'pending-approvals' }
|
|
1095
|
+
}
|
|
1096
|
+
// Condition 4: 0 pending / delivered inquiries
|
|
1097
|
+
const hasOpenInq = Array.isArray(wsBefore.inquiries) && wsBefore.inquiries.some(q => q && (q.status === 'pending' || q.status === 'delivered'))
|
|
1098
|
+
if (hasOpenInq) {
|
|
1099
|
+
return { ok: true, stopped: false, reason: 'pending-inquiries' }
|
|
1100
|
+
}
|
|
1101
|
+
// Condition 2: 0 doing tasks on board
|
|
1102
|
+
const board = deps && deps.boardForSession && deps.boardFileFor
|
|
1103
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
1104
|
+
: null
|
|
1105
|
+
const doingTasks = (board && Array.isArray(board.tasks) ? board.tasks : []).filter(t => t && t.status === 'doing')
|
|
1106
|
+
if (doingTasks.length > 0) {
|
|
1107
|
+
return { ok: true, stopped: false, reason: 'tasks-doing' }
|
|
1108
|
+
}
|
|
1109
|
+
// Condition 5b: empty `recentlyUnpinnedWatch` queue
|
|
1110
|
+
try {
|
|
1111
|
+
const sessOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'session' })
|
|
1112
|
+
const sStore = loadArchiveStore(sessOpt)
|
|
1113
|
+
if (Array.isArray(sStore.recentlyUnpinnedWatch) && sStore.recentlyUnpinnedWatch.length > 0) {
|
|
1114
|
+
return { ok: true, stopped: false, reason: 'unpinned-watch-pending' }
|
|
1115
|
+
}
|
|
1116
|
+
} catch {}
|
|
957
1117
|
|
|
958
1118
|
const hasRunningInSession = (dirObj) => {
|
|
959
1119
|
try {
|
|
@@ -990,16 +1150,26 @@ export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
|
990
1150
|
return false
|
|
991
1151
|
}
|
|
992
1152
|
|
|
1153
|
+
// Condition 1a: 0 running session agents
|
|
993
1154
|
const dirInitial = opts.directory || (deps ? await listPeerDirectory(deps, rootId) : { targets: [] })
|
|
994
1155
|
if (hasRunningInSession(dirInitial)) {
|
|
995
1156
|
return { ok: true, stopped: false, reason: 'agent-running' }
|
|
996
1157
|
}
|
|
997
1158
|
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1159
|
+
// Condition 1b: idle timeout elapsed (or explicit goal-achieved fast stand-down)
|
|
1160
|
+
const rg = (wsBefore.runtimeGuard && typeof wsBefore.runtimeGuard === 'object') ? wsBefore.runtimeGuard : {}
|
|
1161
|
+
const lastActivity = Math.max(Number(rg.lastActivityAt) || 0, Number(rg.autoPilotStartedAt) || 0)
|
|
1162
|
+
const idleTimeoutMs = Math.max(50, Number(effBefore.managedIdleTimeoutMs) || DEFAULT_MANAGED_IDLE_TIMEOUT_MS)
|
|
1163
|
+
if (!opts.goalAchievedFastStop) {
|
|
1164
|
+
if (opts.allowStartupGrace !== false) {
|
|
1165
|
+
const startedAt = Number(rg.autoPilotStartedAt || 0)
|
|
1166
|
+
const hadTurn = Boolean(rg.autoPilotHadTurn)
|
|
1167
|
+
if (!hadTurn && startedAt > 0 && Date.now() - startedAt < Math.min(15_000, idleTimeoutMs)) {
|
|
1168
|
+
return { ok: true, stopped: false, reason: 'startup-grace' }
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
if (lastActivity > 0 && Date.now() - lastActivity < idleTimeoutMs) {
|
|
1172
|
+
return { ok: true, stopped: false, reason: 'idle-timeout-not-reached' }
|
|
1003
1173
|
}
|
|
1004
1174
|
}
|
|
1005
1175
|
|
|
@@ -1036,12 +1206,14 @@ export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
|
1036
1206
|
mutateChiefState((s) => {
|
|
1037
1207
|
const ws = ensureWorkspace(s, rootId)
|
|
1038
1208
|
const effNow = resolveWorkspaceConfig(s, rootId)
|
|
1039
|
-
if (effNow.stopped || effNow.
|
|
1209
|
+
if (effNow.stopped || effNow.runMode !== 'managed') return
|
|
1040
1210
|
if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effNow }
|
|
1211
|
+
ws.config.runMode = 'off'
|
|
1041
1212
|
ws.config.paceMode = 'manual'
|
|
1042
1213
|
ws.config.autoPilot = false
|
|
1043
1214
|
ws.config.autoReview = false
|
|
1044
|
-
if (s.config && s.config.paceMode === 'auto') {
|
|
1215
|
+
if (s.config && (s.config.runMode === 'managed' || s.config.paceMode === 'auto')) {
|
|
1216
|
+
s.config.runMode = 'off'
|
|
1045
1217
|
s.config.paceMode = 'manual'
|
|
1046
1218
|
s.config.autoPilot = false
|
|
1047
1219
|
s.config.autoReview = false
|
|
@@ -1049,8 +1221,9 @@ export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
|
1049
1221
|
ws.chat.push({
|
|
1050
1222
|
id: nextId('chat'),
|
|
1051
1223
|
role: 'chief',
|
|
1052
|
-
|
|
1053
|
-
|
|
1224
|
+
kind: 'receipt',
|
|
1225
|
+
text: '- 【🤖→⏸ 托管自动休眠】连续闲置达阈值且在途任务、待批弹窗、在途问询与卷宗梳理均已清零,已自动将运行模式切换回「⏸ 关停」以节省 Token,随时可再次开启。',
|
|
1226
|
+
actions: ['托管自动休眠'],
|
|
1054
1227
|
at: Date.now(),
|
|
1055
1228
|
})
|
|
1056
1229
|
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|