dsh-chief 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/README.en.md +28 -13
- package/README.md +27 -12
- package/api-routes.js +1274 -0
- package/archive-cabinets.js +766 -0
- package/archive-core.js +761 -0
- package/archive-dossiers.js +1185 -0
- package/archive-precipitated.js +428 -0
- package/archives.js +63 -2991
- package/auto-continue.js +11 -1
- package/board-actions.js +1879 -0
- package/board-schema.js +580 -0
- package/board-store.js +392 -0
- package/chief-approvals.js +841 -0
- package/chief-archives.js +905 -0
- package/chief-commands.js +2513 -0
- package/chief-compaction.js +591 -0
- package/chief-executor.js +859 -153
- package/chief-models.js +578 -0
- package/chief-network.js +720 -0
- package/chief-review.js +1064 -0
- package/chief-state.js +1777 -0
- package/chief-view.js +553 -0
- package/chief.js +94 -7492
- package/client.js +11959 -10923
- package/digest.js +8 -8
- package/index.js +154 -6095
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/model-tools.js +755 -0
- package/package.json +48 -17
- package/runtime-hooks.js +629 -0
- package/subagent-runtime.js +1399 -0
|
@@ -0,0 +1,591 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* chief-compaction.js
|
|
3
|
+
*
|
|
4
|
+
* Idle-wait compaction orchestration, token measurement, rescue harvest, and threshold advisory for DSH Chief.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { getArchiveDetail } from './archives.js'
|
|
8
|
+
import { normalizePermissionMode } from './chief-executor.js'
|
|
9
|
+
import {
|
|
10
|
+
CHAT_CAP,
|
|
11
|
+
archiveTargetForRoot,
|
|
12
|
+
nextId,
|
|
13
|
+
clamp,
|
|
14
|
+
hasValidChiefRiskAck,
|
|
15
|
+
COMPACT_THRESHOLD_MIN_PCT,
|
|
16
|
+
COMPACT_TOKEN_HARD_MIN,
|
|
17
|
+
formatCompactTokenShort,
|
|
18
|
+
resolveWorkspaceConfig,
|
|
19
|
+
normalizeTacticalModes,
|
|
20
|
+
queueChiefApproval,
|
|
21
|
+
loadChiefState,
|
|
22
|
+
mutateChiefState,
|
|
23
|
+
ensureWorkspace,
|
|
24
|
+
extractJsonObject,
|
|
25
|
+
updateChiefConfig,
|
|
26
|
+
} from './chief-state.js'
|
|
27
|
+
import { callChiefLlm } from './chief-models.js'
|
|
28
|
+
import { getChiefView } from './chief-view.js'
|
|
29
|
+
import { harvestTurnDetailsToArchive } from './chief-archives.js'
|
|
30
|
+
|
|
31
|
+
const COMPACT_POLL_MS = 180
|
|
32
|
+
|
|
33
|
+
const COMPACT_IDLE_WAIT_MS = 15_000
|
|
34
|
+
|
|
35
|
+
export async function waitUntilAgentIdle(getStatusFn, timeoutMs = COMPACT_IDLE_WAIT_MS, pollMs = COMPACT_POLL_MS) {
|
|
36
|
+
const deadline = Date.now() + Math.max(200, timeoutMs)
|
|
37
|
+
while (Date.now() < deadline) {
|
|
38
|
+
let status = 'idle'
|
|
39
|
+
try { status = getStatusFn() || 'idle' } catch {}
|
|
40
|
+
if (status !== 'running') return true
|
|
41
|
+
await new Promise(resolve => setTimeout(resolve, pollMs))
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
return (getStatusFn() || 'idle') !== 'running'
|
|
45
|
+
} catch {
|
|
46
|
+
return false
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function measureAgentSessionTokensFallback(agent) {
|
|
51
|
+
if (!agent || !agent.session) return null
|
|
52
|
+
try {
|
|
53
|
+
let totalTokens = 0
|
|
54
|
+
let seq = 0
|
|
55
|
+
let contextWindow = 128_000
|
|
56
|
+
if (typeof agent.session.ownEvents === 'function') {
|
|
57
|
+
const events = agent.session.ownEvents() || []
|
|
58
|
+
seq = events.length
|
|
59
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
60
|
+
const ev = events[i]
|
|
61
|
+
const usage = ev && (ev.usage || (ev.message && ev.message.usage) || (ev.data && ev.data.usage))
|
|
62
|
+
if (usage && typeof usage === 'object') {
|
|
63
|
+
const calc = (Number(usage.inputTokens) || 0)
|
|
64
|
+
+ (Number(usage.cacheReadTokens) || 0)
|
|
65
|
+
+ (Number(usage.outputTokens) || 0)
|
|
66
|
+
totalTokens = Number(usage.totalTokens) || calc
|
|
67
|
+
if (Number(usage.contextWindow) > 0) contextWindow = Number(usage.contextWindow)
|
|
68
|
+
if (totalTokens > 0) break
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return totalTokens > 0 ? { totalTokens, contextWindow, seq } : null
|
|
73
|
+
} catch {
|
|
74
|
+
return null
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Record a visible confirmation card in Chief's right-panel chat when autonomous smart compaction finishes. */
|
|
79
|
+
export function recordSmartCompactionChatReceipt(rootId, { cRes, ratioPct = 0, totalTokens = 0, contextWindow = 0, via = '✦ 智选压缩' } = {}) {
|
|
80
|
+
if (!rootId || rootId === 'global' || !cRes || !cRes.ok || cRes.noop) return
|
|
81
|
+
const usageNote = totalTokens > 0 && contextWindow > 0
|
|
82
|
+
? `(压前占用 ${formatCompactTokenShort(totalTokens)}/${formatCompactTokenShort(contextWindow)} · ${Math.round(ratioPct)}%)`
|
|
83
|
+
: (ratioPct > 0 ? `(压前占用 ${Math.round(ratioPct)}%)` : '')
|
|
84
|
+
const receiptText = `- 【${via}】已先将本轮关键细节抢救入本会话档案柜(#${cRes.harvestId}),并完成主对话静默压缩${usageNote}。`
|
|
85
|
+
mutateChiefState((s) => {
|
|
86
|
+
const ws = ensureWorkspace(s, rootId)
|
|
87
|
+
ws.chat.push({
|
|
88
|
+
id: nextId('chat'),
|
|
89
|
+
role: 'chief',
|
|
90
|
+
text: receiptText,
|
|
91
|
+
actions: ['✦ 智选压缩'],
|
|
92
|
+
at: Date.now(),
|
|
93
|
+
})
|
|
94
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Shared harvest -> disk verification -> host silent compaction sequence (always harvests into Session Cabinet). */
|
|
99
|
+
export async function executeHarvestAndCompact(deps, {
|
|
100
|
+
sid,
|
|
101
|
+
rootId,
|
|
102
|
+
agent = null,
|
|
103
|
+
reason = '',
|
|
104
|
+
seq = 0,
|
|
105
|
+
ratioPct = 0,
|
|
106
|
+
totalTokens = 0,
|
|
107
|
+
contextWindow = 0,
|
|
108
|
+
logLabel = '自动压缩',
|
|
109
|
+
} = {}) {
|
|
110
|
+
if (!sid || !rootId || rootId === 'global') {
|
|
111
|
+
return { ok: false, noop: true, error: '当前为空白新对话(未绑定活跃主会话),暂无可压缩的历史上下文' }
|
|
112
|
+
}
|
|
113
|
+
const focusHint = reason
|
|
114
|
+
|| (ratioPct > 0
|
|
115
|
+
? `上下文占用 ${Math.round(ratioPct)}%(${totalTokens}/${contextWindow} tokens),压缩前抢救现场细节。`
|
|
116
|
+
: '阶段节点前抢救工程现场细节入本会话档案柜。')
|
|
117
|
+
const harvest = await harvestTurnDetailsToArchive(deps, {
|
|
118
|
+
sessionId: rootId,
|
|
119
|
+
agent,
|
|
120
|
+
vaultScope: 'session',
|
|
121
|
+
trigger: 'pre-compaction',
|
|
122
|
+
focusHint,
|
|
123
|
+
})
|
|
124
|
+
if (!harvest || !harvest.ok || !harvest.savedId) {
|
|
125
|
+
return { ok: false, error: 'harvest-failed-abort-compact', detail: harvest && harvest.error }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const targetOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'session' })
|
|
129
|
+
const verified = getArchiveDetail(harvest.savedId, rootId, targetOpt)
|
|
130
|
+
if (!verified || !verified.ok || !verified.item) {
|
|
131
|
+
return { ok: false, error: 'harvest-verify-failed-abort-compact' }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const cmdId = `dsh-chief-compact-${Date.now().toString(36)}`
|
|
135
|
+
let compactRes
|
|
136
|
+
try {
|
|
137
|
+
compactRes = await deps.compactSessionNow(sid, cmdId)
|
|
138
|
+
} catch (err) {
|
|
139
|
+
const errMsg = (err && err.message) || String(err || 'compaction-failed')
|
|
140
|
+
if (!/busy running/i.test(errMsg)) {
|
|
141
|
+
mutateChiefState((s) => {
|
|
142
|
+
const ws = ensureWorkspace(s, rootId)
|
|
143
|
+
ws.runtimeGuard.pendingSmartCompact = null
|
|
144
|
+
})
|
|
145
|
+
}
|
|
146
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
147
|
+
deps.appendBoardLog(
|
|
148
|
+
rootId,
|
|
149
|
+
`⚠️ ${logLabel}未执行(已抢救档案 #${harvest.savedId},计数未变动):${errMsg}`,
|
|
150
|
+
'chief',
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
return { ok: false, error: errMsg, harvestId: harvest.savedId }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (compactRes && compactRes.noop) {
|
|
157
|
+
mutateChiefState((s) => {
|
|
158
|
+
const ws = ensureWorkspace(s, rootId)
|
|
159
|
+
ws.runtimeGuard.pendingSmartCompact = null
|
|
160
|
+
})
|
|
161
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
162
|
+
deps.appendBoardLog(
|
|
163
|
+
rootId,
|
|
164
|
+
`🗄️ ${logLabel}:已先抢救细节入本会话档案柜(#${harvest.savedId}),宿主历史暂无需压缩`,
|
|
165
|
+
'chief',
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
return {
|
|
169
|
+
ok: true,
|
|
170
|
+
noop: true,
|
|
171
|
+
harvestId: harvest.savedId,
|
|
172
|
+
ratioPct: Math.round(ratioPct),
|
|
173
|
+
compactRes,
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
mutateChiefState((s) => {
|
|
178
|
+
const ws = ensureWorkspace(s, rootId)
|
|
179
|
+
ws.runtimeGuard.lastCompactedSeq = seq > 0 ? seq : ((ws.runtimeGuard.lastCompactedSeq || 0) + 1)
|
|
180
|
+
ws.runtimeGuard.lastCompactedAt = Date.now()
|
|
181
|
+
ws.runtimeGuard.autoCompactCount = (ws.runtimeGuard.autoCompactCount || 0) + 1
|
|
182
|
+
ws.runtimeGuard.pendingSmartCompact = null
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
186
|
+
deps.appendBoardLog(
|
|
187
|
+
rootId,
|
|
188
|
+
`🗜️ ${logLabel}:已先抢救细节入本会话档案柜(#${harvest.savedId})并执行静默压缩${ratioPct > 0 ? `(占 ${Math.round(ratioPct)}%)` : ''}`,
|
|
189
|
+
'chief',
|
|
190
|
+
)
|
|
191
|
+
}
|
|
192
|
+
return {
|
|
193
|
+
ok: true,
|
|
194
|
+
noop: false,
|
|
195
|
+
harvestId: harvest.savedId,
|
|
196
|
+
ratioPct: Math.round(ratioPct),
|
|
197
|
+
compactRes,
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Called by Lead via `chief_board({ action: "context.compact", text })` when `✦ 智选` co-management is enabled. */
|
|
202
|
+
export async function requestSmartCompactFromLead(deps, {
|
|
203
|
+
sessionId = '',
|
|
204
|
+
reason = '',
|
|
205
|
+
by = 'lead',
|
|
206
|
+
} = {}) {
|
|
207
|
+
const sid = String(sessionId || '').trim()
|
|
208
|
+
if (!sid) return { ok: false, error: '当前未绑定具体会话,无法发起智选压缩' }
|
|
209
|
+
const rootId = (deps && deps.resolveRootSessionId ? deps.resolveRootSessionId(sid) : '') || sid
|
|
210
|
+
const state = loadChiefState()
|
|
211
|
+
const effCfg = resolveWorkspaceConfig(state, rootId)
|
|
212
|
+
const tactical = normalizeTacticalModes(effCfg.tacticalModes)
|
|
213
|
+
if (!tactical.smartCompact && !tactical.autoCompact) {
|
|
214
|
+
return { ok: false, error: '当前未开启「✦ 智选」或自动压缩模式,请先在战术菜单打开开关' }
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const cleanReason = clamp(reason || '主会话判断阶段已收口,主动协同发起归档压缩', 240)
|
|
218
|
+
mutateChiefState((s) => {
|
|
219
|
+
const ws = ensureWorkspace(s, rootId)
|
|
220
|
+
ws.runtimeGuard.pendingSmartCompact = {
|
|
221
|
+
at: Date.now(),
|
|
222
|
+
reason: cleanReason,
|
|
223
|
+
by: clamp(by || 'lead', 40),
|
|
224
|
+
}
|
|
225
|
+
})
|
|
226
|
+
|
|
227
|
+
let status = 'idle'
|
|
228
|
+
try {
|
|
229
|
+
if (deps && typeof deps.getAgentStatus === 'function') {
|
|
230
|
+
status = deps.getAgentStatus(sid) || 'idle'
|
|
231
|
+
}
|
|
232
|
+
} catch {}
|
|
233
|
+
|
|
234
|
+
if (status === 'running' || !deps || typeof deps.compactSessionNow !== 'function') {
|
|
235
|
+
return {
|
|
236
|
+
ok: true,
|
|
237
|
+
queued: true,
|
|
238
|
+
reason: cleanReason,
|
|
239
|
+
message: '已登记主会话的智选归档压缩请求,本轮收口空闲后将由参谋长抢救细节入本会话档案柜并静默压缩。',
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
let usage = null
|
|
244
|
+
try {
|
|
245
|
+
if (typeof deps.measureSessionTokens === 'function') {
|
|
246
|
+
usage = await deps.measureSessionTokens(sid)
|
|
247
|
+
}
|
|
248
|
+
} catch {}
|
|
249
|
+
const contextWindow = Math.max(1000, Number(usage && usage.contextWindow) || 128_000)
|
|
250
|
+
const totalTokens = Number(usage && usage.totalTokens) || 0
|
|
251
|
+
const seq = Math.max(0, Math.round(Number(usage && usage.seq) || 0))
|
|
252
|
+
const ratioPct = totalTokens > 0 ? (totalTokens / contextWindow) * 100 : 0
|
|
253
|
+
|
|
254
|
+
const execRes = await executeHarvestAndCompact(deps, {
|
|
255
|
+
sid,
|
|
256
|
+
rootId,
|
|
257
|
+
reason: cleanReason,
|
|
258
|
+
seq,
|
|
259
|
+
ratioPct,
|
|
260
|
+
totalTokens,
|
|
261
|
+
contextWindow,
|
|
262
|
+
logLabel: '✦ 智选压缩(主会话协同)',
|
|
263
|
+
})
|
|
264
|
+
return { ...execRes, compacted: Boolean(execRes && execRes.ok), reason: cleanReason }
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Post-Turn Auto-Compaction Pipeline (strict safety contract):
|
|
269
|
+
* 1. NEVER run inside synchronous `turn-stopping` or while agent.status === 'running'. Wait for idle first.
|
|
270
|
+
* 2. When `smartCompact` (`✦ 智选`) is enabled, hard `compactThresholdPct` is bypassed completely!
|
|
271
|
+
* Compaction runs ONLY on `pendingSmartCompact` (from Lead or Chief) or Chief's `shouldCompactNow` judgment.
|
|
272
|
+
* 3. Always harvest into Session Cabinet + verify on disk BEFORE calling `compactSessionNow`.
|
|
273
|
+
*/
|
|
274
|
+
export async function maybeRunPreCompaction(deps, {
|
|
275
|
+
agent = null,
|
|
276
|
+
sessionId = '',
|
|
277
|
+
rootId: explicitRootId = '',
|
|
278
|
+
bypassIdleWait = false,
|
|
279
|
+
} = {}) {
|
|
280
|
+
const sid = String(sessionId || (agent && agent.id) || '').trim()
|
|
281
|
+
if (!sid) return { ok: false, skipped: 'no-session' }
|
|
282
|
+
const rootId = explicitRootId || (deps && deps.resolveRootSessionId ? deps.resolveRootSessionId(sid, agent) : '') || sid
|
|
283
|
+
|
|
284
|
+
const state = loadChiefState()
|
|
285
|
+
const effCfg = resolveWorkspaceConfig(state, rootId)
|
|
286
|
+
if (effCfg.stopped || effCfg.paceMode === 'stopped') {
|
|
287
|
+
return { ok: false, skipped: 'chief-stopped' }
|
|
288
|
+
}
|
|
289
|
+
const tactical = normalizeTacticalModes(effCfg.tacticalModes)
|
|
290
|
+
const wsSnapshot = ensureWorkspace(state, rootId)
|
|
291
|
+
const hasAck = hasValidChiefRiskAck(wsSnapshot)
|
|
292
|
+
const permMode = normalizePermissionMode(effCfg.permissionMode, { requireAck: true, hasChiefRiskAck: hasAck })
|
|
293
|
+
const pendingSmart = wsSnapshot.runtimeGuard && wsSnapshot.runtimeGuard.pendingSmartCompact
|
|
294
|
+
|
|
295
|
+
if (!pendingSmart && !tactical.autoCompact && !tactical.smartCompact) {
|
|
296
|
+
return { ok: false, skipped: 'disabled' }
|
|
297
|
+
}
|
|
298
|
+
if (!deps || typeof deps.compactSessionNow !== 'function') return { ok: false, skipped: 'no-compaction-service' }
|
|
299
|
+
|
|
300
|
+
if (permMode === 'advisor' || permMode === 'assistant') {
|
|
301
|
+
return { ok: false, skipped: 'permission-mode', permissionMode: permMode }
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// When `✦ 智选` is enabled and no pending smart request exists, hard threshold does NOT trigger!
|
|
305
|
+
if (!pendingSmart && tactical.smartCompact) {
|
|
306
|
+
return { ok: false, skipped: 'smart-compact-mode', mode: 'smart' }
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const getStatus = () => {
|
|
310
|
+
if (typeof deps.getAgentStatus === 'function') return deps.getAgentStatus(sid)
|
|
311
|
+
return (agent && agent.status) || 'idle'
|
|
312
|
+
}
|
|
313
|
+
if (getStatus() === 'running') {
|
|
314
|
+
if (bypassIdleWait) return { ok: false, skipped: 'running' }
|
|
315
|
+
const becameIdle = await waitUntilAgentIdle(getStatus)
|
|
316
|
+
if (!becameIdle) return { ok: false, skipped: 'busy-running' }
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
let usage = null
|
|
320
|
+
try {
|
|
321
|
+
usage = typeof deps.measureSessionTokens === 'function'
|
|
322
|
+
? await deps.measureSessionTokens(sid, agent)
|
|
323
|
+
: measureAgentSessionTokensFallback(agent)
|
|
324
|
+
} catch {}
|
|
325
|
+
|
|
326
|
+
if (pendingSmart) {
|
|
327
|
+
const contextWindow = Math.max(1000, Number(usage && usage.contextWindow) || 128_000)
|
|
328
|
+
const totalTokens = Number(usage && usage.totalTokens) || 0
|
|
329
|
+
const seq = Math.max(0, Math.round(Number(usage && usage.seq) || 0))
|
|
330
|
+
const ratioPct = totalTokens > 0 ? (totalTokens / contextWindow) * 100 : 0
|
|
331
|
+
if (permMode === 'strategist') {
|
|
332
|
+
const dedupeKey = `auto_compact:smart:${sid}:${pendingSmart.at || seq}`
|
|
333
|
+
const apr = queueChiefApproval(rootId, {
|
|
334
|
+
category: 'main_workflow',
|
|
335
|
+
operationLabel: '✦ 智选压缩主对话上下文 (/compact)',
|
|
336
|
+
targetLabel: '当前主会话',
|
|
337
|
+
reason: pendingSmart.reason || '主会话/参谋评估阶段收口,请求压缩历史上下文',
|
|
338
|
+
impact: '将先抢救现场细节入本会话档案柜,再静默压缩主对话历史',
|
|
339
|
+
dedupeKey,
|
|
340
|
+
kind: 'compact',
|
|
341
|
+
payload: { reason: pendingSmart.reason || '✦ 智选协同触发压缩' },
|
|
342
|
+
by: pendingSmart.by || 'chief',
|
|
343
|
+
})
|
|
344
|
+
return { ok: false, pendingApproval: true, approvalId: apr && apr.id, skipped: 'pending-approval' }
|
|
345
|
+
}
|
|
346
|
+
const out = await executeHarvestAndCompact(deps, {
|
|
347
|
+
sid,
|
|
348
|
+
rootId,
|
|
349
|
+
agent,
|
|
350
|
+
reason: pendingSmart.reason || '主会话/参谋长智选协同触发压缩',
|
|
351
|
+
seq,
|
|
352
|
+
ratioPct,
|
|
353
|
+
totalTokens,
|
|
354
|
+
contextWindow,
|
|
355
|
+
logLabel: '✦ 智选压缩',
|
|
356
|
+
})
|
|
357
|
+
const actuallyCompacted = Boolean(out && out.ok && !out.noop)
|
|
358
|
+
if (actuallyCompacted) {
|
|
359
|
+
recordSmartCompactionChatReceipt(rootId, {
|
|
360
|
+
cRes: out,
|
|
361
|
+
ratioPct,
|
|
362
|
+
totalTokens,
|
|
363
|
+
contextWindow,
|
|
364
|
+
via: '✦ 智选压缩',
|
|
365
|
+
})
|
|
366
|
+
}
|
|
367
|
+
return { ...out, smartCompacted: actuallyCompacted }
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
if (!usage || !Number(usage.totalTokens)) {
|
|
371
|
+
return { ok: false, skipped: 'no-token-usage' }
|
|
372
|
+
}
|
|
373
|
+
const contextWindow = Math.max(1000, Number(usage.contextWindow) || 128_000)
|
|
374
|
+
const totalTokens = Number(usage.totalTokens) || 0
|
|
375
|
+
const seq = Math.max(0, Math.round(Number(usage.seq) || 0))
|
|
376
|
+
const ratioPct = (totalTokens / contextWindow) * 100
|
|
377
|
+
const lastSeq = (wsSnapshot.runtimeGuard && wsSnapshot.runtimeGuard.lastCompactedSeq) || 0
|
|
378
|
+
|
|
379
|
+
const thresholdMode = tactical.compactThresholdMode === 'tokens' ? 'tokens' : 'pct'
|
|
380
|
+
let limitHint = ''
|
|
381
|
+
if (thresholdMode === 'tokens') {
|
|
382
|
+
const thresholdTokens = Math.max(COMPACT_TOKEN_HARD_MIN, Number(tactical.compactThresholdTokens) || 64_000)
|
|
383
|
+
if (totalTokens < thresholdTokens) {
|
|
384
|
+
return {
|
|
385
|
+
ok: false,
|
|
386
|
+
skipped: 'below-threshold',
|
|
387
|
+
mode: 'tokens',
|
|
388
|
+
totalTokens,
|
|
389
|
+
thresholdTokens,
|
|
390
|
+
thresholdInput: formatCompactTokenShort(thresholdTokens),
|
|
391
|
+
ratioPct: Math.round(ratioPct),
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
limitHint = `上下文占用 ${formatCompactTokenShort(totalTokens)} 已达到自定阈值 ${formatCompactTokenShort(thresholdTokens)}`
|
|
395
|
+
} else {
|
|
396
|
+
const minPct = Math.max(COMPACT_THRESHOLD_MIN_PCT, Number(tactical.compactThresholdPct) || 80)
|
|
397
|
+
if (ratioPct < minPct) {
|
|
398
|
+
return {
|
|
399
|
+
ok: false,
|
|
400
|
+
skipped: 'below-threshold',
|
|
401
|
+
mode: 'pct',
|
|
402
|
+
ratioPct: Math.round(ratioPct),
|
|
403
|
+
thresholdPct: minPct,
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
limitHint = `上下文占用已达 ${Math.round(ratioPct)}%(阈值 ${minPct}%,${totalTokens}/${contextWindow} tokens)`
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if (seq > 0 && seq <= lastSeq) {
|
|
410
|
+
return { ok: false, skipped: 'already-compacted-seq', seq, lastSeq }
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
if (permMode === 'strategist') {
|
|
414
|
+
const dedupeKey = `auto_compact:thresh:${sid}:${seq || Math.round(ratioPct)}`
|
|
415
|
+
const apr = queueChiefApproval(rootId, {
|
|
416
|
+
category: 'main_workflow',
|
|
417
|
+
operationLabel: '自动抢救并压缩主对话上下文 (/compact)',
|
|
418
|
+
targetLabel: '当前主会话',
|
|
419
|
+
reason: `${limitHint},L2 参谋模式需您逐项授权后执行压缩。`,
|
|
420
|
+
impact: '将先抢救细节入本会话档案柜,随后压缩裁剪主对话历史上下文',
|
|
421
|
+
dedupeKey,
|
|
422
|
+
kind: 'compact',
|
|
423
|
+
payload: { reason: `${limitHint},压缩前抢救现场细节。` },
|
|
424
|
+
by: 'chief',
|
|
425
|
+
})
|
|
426
|
+
return { ok: false, pendingApproval: true, approvalId: apr && apr.id, skipped: 'pending-approval' }
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
return executeHarvestAndCompact(deps, {
|
|
430
|
+
sid,
|
|
431
|
+
rootId,
|
|
432
|
+
agent,
|
|
433
|
+
reason: `${limitHint},压缩前抢救现场细节。`,
|
|
434
|
+
seq,
|
|
435
|
+
ratioPct,
|
|
436
|
+
totalTokens,
|
|
437
|
+
contextWindow,
|
|
438
|
+
logLabel: '自动压缩',
|
|
439
|
+
})
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
export function buildChiefCompactFn(deps, rootId) {
|
|
443
|
+
return async (reason) => {
|
|
444
|
+
if (!rootId || rootId === 'global') {
|
|
445
|
+
return { ok: false, noop: true, skipped: 'blank-context', error: '当前为空白新对话(未绑定活跃主会话),暂无可压缩的历史上下文' }
|
|
446
|
+
}
|
|
447
|
+
if (!deps || typeof deps.compactSessionNow !== 'function') {
|
|
448
|
+
return { ok: false, skipped: 'no-compaction-service', error: '宿主压缩服务未挂载' }
|
|
449
|
+
}
|
|
450
|
+
let usage = null
|
|
451
|
+
try {
|
|
452
|
+
usage = typeof deps.measureSessionTokens === 'function'
|
|
453
|
+
? await deps.measureSessionTokens(rootId)
|
|
454
|
+
: null
|
|
455
|
+
} catch {}
|
|
456
|
+
const contextWindow = Math.max(1000, Number(usage && usage.contextWindow) || 128_000)
|
|
457
|
+
const totalTokens = Number(usage && usage.totalTokens) || 0
|
|
458
|
+
const seq = Math.max(0, Math.round(Number(usage && usage.seq) || 0))
|
|
459
|
+
const ratioPct = totalTokens > 0 ? (totalTokens / contextWindow) * 100 : 0
|
|
460
|
+
return executeHarvestAndCompact(deps, {
|
|
461
|
+
sid: rootId,
|
|
462
|
+
rootId,
|
|
463
|
+
reason: reason || '参谋长实权工具主动发起抢救与上下文压缩',
|
|
464
|
+
seq,
|
|
465
|
+
ratioPct,
|
|
466
|
+
totalTokens,
|
|
467
|
+
contextWindow,
|
|
468
|
+
logLabel: '参谋长主动压缩',
|
|
469
|
+
})
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
const COMPACT_ADVISOR_SYSTEM = `你是 DSH 参谋长的「上下文与自动压缩策略顾问」。
|
|
474
|
+
用户点击了「参谋智设」自动压缩阈值按钮。请结合当前会话的模型上下文窗口、固定开销(系统提示词 + 工具定义)、已用消息数以及当前任务复杂度,给出最合理的自动压缩触发阈值百分比(必须是 5 的倍数,且严格落在给定 [floorPct, 90] 安全区间内)。
|
|
475
|
+
|
|
476
|
+
设计原则:
|
|
477
|
+
1. 若系统提示词+工具开销已经占用了较大比例,或上下文窗口 <= 200K,阈值绝对不能过低,否则连系统提示词都装不满就反复触发压缩,严重降智!
|
|
478
|
+
2. 若上下文窗口极大(如 1M 上下文,固定开销只占 ~5%),可适当设低(如 25%~40%,即 250K~400K 左右)来保持模型注意力敏锐度与高速响应,同时留出充足工作空间。
|
|
479
|
+
3. 请仅返回合法 JSON 对象:
|
|
480
|
+
{
|
|
481
|
+
"recommendedPct": 30,
|
|
482
|
+
"reason": "当前 1M 窗口中固定开销约 52K(5%),30%(约 300K)既能维持长程理解又能防止注意力衰退。"
|
|
483
|
+
}`
|
|
484
|
+
|
|
485
|
+
export async function recommendAndSetCompactThreshold(deps, { sessionId = '' } = {}) {
|
|
486
|
+
const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
|
|
487
|
+
const rawUsage = typeof deps.measureSessionTokens === 'function'
|
|
488
|
+
? await Promise.resolve(deps.measureSessionTokens(rootId))
|
|
489
|
+
: null
|
|
490
|
+
const usage = (rawUsage && typeof rawUsage === 'object') ? rawUsage : {}
|
|
491
|
+
|
|
492
|
+
const contextWindow = Math.max(32000, Number(usage.contextWindow) || 128000)
|
|
493
|
+
const systemTokens = Math.max(0, Number(usage.systemTokens) || 0)
|
|
494
|
+
const toolsTokens = Math.max(0, Number(usage.toolsTokens) || 0)
|
|
495
|
+
const messageTokens = Math.max(0, Number(usage.messageTokens) || 0)
|
|
496
|
+
const usedTokens = Math.max(0, Number(usage.usedTokens) || (systemTokens + toolsTokens + messageTokens))
|
|
497
|
+
const overheadTokens = systemTokens + toolsTokens
|
|
498
|
+
const modelRef = String(usage.modelRef || '').trim()
|
|
499
|
+
|
|
500
|
+
const minSafeTokens = Math.max(Math.round(overheadTokens * 2.2), overheadTokens + 45000, 48000)
|
|
501
|
+
const rawFloorPct = Math.ceil(((minSafeTokens / contextWindow) * 100) / 5) * 5
|
|
502
|
+
const floorPct = Math.min(85, Math.max(15, rawFloorPct))
|
|
503
|
+
|
|
504
|
+
const basePct = contextWindow >= 800000
|
|
505
|
+
? 35
|
|
506
|
+
: contextWindow >= 350000
|
|
507
|
+
? 55
|
|
508
|
+
: contextWindow >= 180000
|
|
509
|
+
? 65
|
|
510
|
+
: 75
|
|
511
|
+
const heuristicPct = Math.min(90, Math.max(floorPct, basePct))
|
|
512
|
+
|
|
513
|
+
const fmtTok = (n) => {
|
|
514
|
+
const v = Math.max(0, Math.round(Number(n) || 0))
|
|
515
|
+
if (v >= 1000000) return `${(v / 1000000).toFixed(v % 1000000 === 0 ? 0 : 1)}M`
|
|
516
|
+
if (v >= 1000) return `${Math.round(v / 1000)}K`
|
|
517
|
+
return String(v)
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
let finalPct = heuristicPct
|
|
521
|
+
let llmGuided = false
|
|
522
|
+
let reason = `当前窗口 ${fmtTok(contextWindow)}(系统与工具固定开销 ~${fmtTok(overheadTokens)}),已自动锁定在 ${finalPct}%(~${fmtTok((contextWindow * finalPct) / 100)}),兼顾推理深度与防劣化安全底线。`
|
|
523
|
+
|
|
524
|
+
const board = typeof deps.boardForSession === 'function' && typeof deps.boardFileFor === 'function'
|
|
525
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
526
|
+
: null
|
|
527
|
+
const objective = board && board.objective ? clamp(board.objective, 160) : '(未设总目标)'
|
|
528
|
+
const activeTaskCount = Array.isArray(board?.tasks)
|
|
529
|
+
? board.tasks.filter(t => t && (t.status === 'doing' || t.status === 'todo' || t.status === 'blocked')).length
|
|
530
|
+
: 0
|
|
531
|
+
|
|
532
|
+
try {
|
|
533
|
+
const advisorPrompt = [
|
|
534
|
+
`- 当前主对话模型: ${modelRef || '默认对话模型'}`,
|
|
535
|
+
`- 上下文总窗口 (contextWindow): ${contextWindow} tokens (${fmtTok(contextWindow)})`,
|
|
536
|
+
`- 系统提示词 (systemTokens): ${systemTokens} tokens (${fmtTok(systemTokens)})`,
|
|
537
|
+
`- 工具定义 (toolsTokens): ${toolsTokens} tokens (${fmtTok(toolsTokens)})`,
|
|
538
|
+
`- 固定开销合计 (overhead): ${overheadTokens} tokens (${((overheadTokens / contextWindow) * 100).toFixed(1)}%)`,
|
|
539
|
+
`- 当前已用总上下文: ${usedTokens} tokens (${((usedTokens / contextWindow) * 100).toFixed(1)}%)`,
|
|
540
|
+
`- 系统硬性安全下限 (floorPct): ${floorPct}% (~${fmtTok((contextWindow * floorPct) / 100)})`,
|
|
541
|
+
`- 启发式基准建议: ${heuristicPct}%`,
|
|
542
|
+
`- 当前任务目标: ${objective}(活跃任务 ${activeTaskCount} 项)`,
|
|
543
|
+
'',
|
|
544
|
+
`请给出 final recommendedPct(5 的倍数,范围 [${floorPct}, 90])与一句不超过 85 字的中文建议理由。`,
|
|
545
|
+
].join('\n')
|
|
546
|
+
|
|
547
|
+
const llmRes = await callChiefLlm(deps, {
|
|
548
|
+
sessionId: rootId,
|
|
549
|
+
system: COMPACT_ADVISOR_SYSTEM,
|
|
550
|
+
prompt: advisorPrompt,
|
|
551
|
+
maxTokens: 320,
|
|
552
|
+
})
|
|
553
|
+
if (llmRes && llmRes.ok && llmRes.text) {
|
|
554
|
+
const parsed = extractJsonObject(llmRes.text)
|
|
555
|
+
if (parsed && Number.isFinite(Number(parsed.recommendedPct))) {
|
|
556
|
+
const snapped = Math.round(Number(parsed.recommendedPct) / 5) * 5
|
|
557
|
+
finalPct = Math.min(90, Math.max(floorPct, snapped))
|
|
558
|
+
if (typeof parsed.reason === 'string' && parsed.reason.trim()) {
|
|
559
|
+
reason = clamp(parsed.reason.trim(), 180)
|
|
560
|
+
}
|
|
561
|
+
llmGuided = true
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
} catch {}
|
|
565
|
+
|
|
566
|
+
updateChiefConfig({
|
|
567
|
+
sessionId: rootId,
|
|
568
|
+
tacticalModes: {
|
|
569
|
+
compactThresholdPct: finalPct,
|
|
570
|
+
autoCompact: true,
|
|
571
|
+
},
|
|
572
|
+
})
|
|
573
|
+
|
|
574
|
+
const view = await getChiefView(deps, rootId, { autoSummarize: false })
|
|
575
|
+
return {
|
|
576
|
+
ok: true,
|
|
577
|
+
recommendedPct: finalPct,
|
|
578
|
+
triggerTokens: Math.round((contextWindow * finalPct) / 100),
|
|
579
|
+
overheadTokens,
|
|
580
|
+
contextWindow,
|
|
581
|
+
systemTokens,
|
|
582
|
+
toolsTokens,
|
|
583
|
+
messageTokens,
|
|
584
|
+
usedTokens,
|
|
585
|
+
floorPct,
|
|
586
|
+
modelRef,
|
|
587
|
+
llmGuided,
|
|
588
|
+
reason,
|
|
589
|
+
view,
|
|
590
|
+
}
|
|
591
|
+
}
|