dsh-chief 1.2.1 → 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 +47 -16
- package/README.en.md +5 -3
- package/README.md +5 -3
- 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/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 +196 -22
- 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 -8541
- package/client.js +11834 -11638
- package/index.js +154 -6363
- package/model-tools.js +755 -0
- package/package.json +28 -1
- package/runtime-hooks.js +629 -0
- package/subagent-runtime.js +1399 -0
|
@@ -0,0 +1,841 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* chief-approvals.js
|
|
3
|
+
*
|
|
4
|
+
* Human decision handlers for suggestions, L2 per-action approvals, and permission elevations for DSH Chief.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
DEFAULT_CHIEF_PERMISSION_MODE,
|
|
9
|
+
CHIEF_PERMISSION_META,
|
|
10
|
+
normalizePermissionMode,
|
|
11
|
+
permissionRank,
|
|
12
|
+
evaluateSafetyGuardHardRules,
|
|
13
|
+
executeChiefToolCall,
|
|
14
|
+
} from './chief-executor.js'
|
|
15
|
+
import {
|
|
16
|
+
CHAT_CAP,
|
|
17
|
+
MAIL_CAP,
|
|
18
|
+
resolveSessionWorkspaceCwd,
|
|
19
|
+
nextId,
|
|
20
|
+
clamp,
|
|
21
|
+
cleanMultiline,
|
|
22
|
+
hasValidChiefRiskAck,
|
|
23
|
+
computeApprovalPayloadHash,
|
|
24
|
+
upsertResumeTaskOnWs,
|
|
25
|
+
pushAuditToWs,
|
|
26
|
+
normalizeMail,
|
|
27
|
+
resolveWorkspaceConfig,
|
|
28
|
+
appendChiefAuditLog,
|
|
29
|
+
loadChiefState,
|
|
30
|
+
mutateChiefState,
|
|
31
|
+
getLinkedCluster,
|
|
32
|
+
ensureWorkspace,
|
|
33
|
+
updateChiefConfig,
|
|
34
|
+
} from './chief-state.js'
|
|
35
|
+
import { deliverCrossMessage } from './chief-network.js'
|
|
36
|
+
import { getChiefView } from './chief-view.js'
|
|
37
|
+
import { buildChiefArchiveUpsertFn } from './chief-archives.js'
|
|
38
|
+
import { buildChiefCompactFn, recordSmartCompactionChatReceipt } from './chief-compaction.js'
|
|
39
|
+
import { askOrCommandChief } from './chief-commands.js'
|
|
40
|
+
|
|
41
|
+
export async function handleSuggestionDecision(deps, { sessionId, suggestionId, decision, editedText, boundField, pinGlobal }) {
|
|
42
|
+
const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
|
|
43
|
+
let found = null
|
|
44
|
+
mutateChiefState((state) => {
|
|
45
|
+
const ws = ensureWorkspace(state, rootId)
|
|
46
|
+
const item = ws.suggestions.find(s => s.id === suggestionId)
|
|
47
|
+
if (!item) return
|
|
48
|
+
item.status = decision === 'approve' ? 'applied' : 'dismissed'
|
|
49
|
+
found = { ...item }
|
|
50
|
+
})
|
|
51
|
+
if (!found) return { ok: false, error: '未找到该请示或建议卡片' }
|
|
52
|
+
|
|
53
|
+
if (decision === 'approve' && found.kind === 'bound') {
|
|
54
|
+
const rawBf = String(boundField || '').trim().toLowerCase()
|
|
55
|
+
const normBf = rawBf === 'must' ? 'allowed' : rawBf
|
|
56
|
+
const rawFoundBf = String(found.boundField || '').trim().toLowerCase()
|
|
57
|
+
const normFoundBf = rawFoundBf === 'must' ? 'allowed' : rawFoundBf
|
|
58
|
+
const col = ['forbidden', 'allowed', 'notes'].includes(normBf)
|
|
59
|
+
? normBf
|
|
60
|
+
: (['forbidden', 'allowed', 'notes'].includes(normFoundBf) ? normFoundBf : 'forbidden')
|
|
61
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '必做事项', notes: '注意事项' }
|
|
62
|
+
const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
|
|
63
|
+
const ruleText = clamp(editedText || found.draftText || found.title, 220)
|
|
64
|
+
if (!ruleText) return { ok: false, error: '边界条文不能为空' }
|
|
65
|
+
|
|
66
|
+
const shouldPin = typeof pinGlobal === 'boolean' ? pinGlobal : Boolean(found.pinGlobal)
|
|
67
|
+
const replaces = Array.isArray(found.replaces) ? found.replaces.filter(Boolean) : []
|
|
68
|
+
|
|
69
|
+
const writeRes = deps.runAction
|
|
70
|
+
? (replaces.length > 0
|
|
71
|
+
? deps.runAction({
|
|
72
|
+
action: 'bounds.consolidate',
|
|
73
|
+
field: col,
|
|
74
|
+
removeItems: replaces,
|
|
75
|
+
item: ruleText,
|
|
76
|
+
pinned: shouldPin,
|
|
77
|
+
session: rootId === 'global' ? '' : rootId,
|
|
78
|
+
by: 'DSH 参谋长',
|
|
79
|
+
})
|
|
80
|
+
: deps.runAction({
|
|
81
|
+
action: 'bounds.add',
|
|
82
|
+
field: col,
|
|
83
|
+
item: ruleText,
|
|
84
|
+
pinned: shouldPin,
|
|
85
|
+
session: rootId === 'global' ? '' : rootId,
|
|
86
|
+
by: 'DSH 参谋长',
|
|
87
|
+
}))
|
|
88
|
+
: { ok: false, error: 'runAction unavailable' }
|
|
89
|
+
if (!writeRes || !writeRes.ok) {
|
|
90
|
+
return { ok: false, error: (writeRes && writeRes.error) || '写入边界失败' }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const scopeTag = shouldPin ? '📌 全局共享边界(跨任务生效)' : '本任务边界(仅当前会话树生效)'
|
|
94
|
+
// Broadcast a silent boundary decree so running lead/subagents immediately see the new rule on next pre-step
|
|
95
|
+
mutateChiefState((state) => {
|
|
96
|
+
const ws = ensureWorkspace(state, rootId)
|
|
97
|
+
const cluster = getLinkedCluster(state, rootId)
|
|
98
|
+
const decree = normalizeMail({
|
|
99
|
+
from: 'DSH 参谋长 (边界颁布)',
|
|
100
|
+
fromSession: rootId === 'global' ? '' : rootId,
|
|
101
|
+
fromRootId: rootId === 'global' ? '' : rootId,
|
|
102
|
+
to: 'all',
|
|
103
|
+
toSession: 'all',
|
|
104
|
+
toRootId: 'all',
|
|
105
|
+
participantRoots: cluster,
|
|
106
|
+
channelType: cluster.length > 1 ? 'broadcast' : 'internal',
|
|
107
|
+
broadcastId: nextId('bcast'),
|
|
108
|
+
subject: `用户已批准${replaces.length ? `浓缩${colLabel}(${replaces.length} 合 1)` : `新${colLabel}`}`,
|
|
109
|
+
text: `- 【${colLabel} · ${scopeTag}】${shouldPin ? '📌 ' : ''}${ruleText}${replaces.length ? `\n- 【已整合替代】原 ${replaces.length} 条零散边界已合并为此条总则` : ''}${found.reason ? `\n- 【缘由】${found.reason}` : ''}\n请主代理与全体子代理自即刻起严格遵守!`,
|
|
110
|
+
mode: 'silent',
|
|
111
|
+
deliveredPhysical: false,
|
|
112
|
+
})
|
|
113
|
+
if (decree) {
|
|
114
|
+
ws.mailbox.push(decree)
|
|
115
|
+
if (ws.mailbox.length > MAIL_CAP) ws.mailbox = ws.mailbox.slice(-MAIL_CAP)
|
|
116
|
+
}
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
ok: true,
|
|
121
|
+
boundApplied: { field: col, label: colLabel, item: ruleText, pinned: shouldPin, replacedCount: replaces.length },
|
|
122
|
+
view: await getChiefView(deps, rootId, { autoSummarize: true }),
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (decision === 'approve' && found.kind === 'goal_approval') {
|
|
127
|
+
const res = deps.runAction
|
|
128
|
+
? deps.runAction({ action: 'goal.approve', session: rootId, by: 'user' })
|
|
129
|
+
: { ok: false, error: 'runAction unavailable' }
|
|
130
|
+
return {
|
|
131
|
+
ok: Boolean(res && res.ok),
|
|
132
|
+
goalApproved: true,
|
|
133
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (decision !== 'approve' && found.kind === 'goal_approval') {
|
|
138
|
+
const res = deps.runAction
|
|
139
|
+
? deps.runAction({
|
|
140
|
+
action: 'goal.reject',
|
|
141
|
+
reason: editedText || '暂不结项,继续推进完善',
|
|
142
|
+
session: rootId,
|
|
143
|
+
by: 'user',
|
|
144
|
+
})
|
|
145
|
+
: { ok: false }
|
|
146
|
+
return {
|
|
147
|
+
ok: Boolean(res && res.ok),
|
|
148
|
+
goalRejected: true,
|
|
149
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (decision === 'approve' && (found.kind === 'relay' || found.kind === 'advice')) {
|
|
154
|
+
const body = editedText ? cleanMultiline(editedText, 1200) : found.draftText
|
|
155
|
+
const deliverTarget = found.target || 'lead'
|
|
156
|
+
const shouldDeliver = Boolean(body && deliverTarget !== 'none' && deliverTarget !== 'chief')
|
|
157
|
+
const delivery = shouldDeliver
|
|
158
|
+
? await deliverCrossMessage(deps, {
|
|
159
|
+
fromSession: rootId,
|
|
160
|
+
fromLabel: found.kind === 'advice' ? 'DSH 参谋长 (获批进言)' : 'DSH 参谋长 (获批建议)',
|
|
161
|
+
target: deliverTarget,
|
|
162
|
+
subject: found.title,
|
|
163
|
+
text: body,
|
|
164
|
+
mode: found.mode || (found.kind === 'advice' ? 'followup' : 'steer'),
|
|
165
|
+
})
|
|
166
|
+
: { ok: true, skippedDelivery: true }
|
|
167
|
+
if (found.kind === 'advice' && typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
168
|
+
deps.appendBoardLog(rootId, `💡 用户已拍板采纳参谋进言:${clamp(found.title, 40)}`, 'user')
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
ok: delivery.ok !== false,
|
|
172
|
+
adviceApplied: found.kind === 'advice',
|
|
173
|
+
delivery,
|
|
174
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return {
|
|
179
|
+
ok: true,
|
|
180
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** 统一批量执行当前授权边界内的待处理建议并产出单一结构化回执(Bundle 4)。 */
|
|
185
|
+
export async function executeBatchSuggestions(deps, {
|
|
186
|
+
sessionId = '',
|
|
187
|
+
ids = [],
|
|
188
|
+
includeGoalApproval = false,
|
|
189
|
+
pinGlobalDefault = undefined,
|
|
190
|
+
} = {}) {
|
|
191
|
+
const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : '') || String(sessionId || 'global')
|
|
192
|
+
const stateSnap = loadChiefState()
|
|
193
|
+
const wsSnap = ensureWorkspace(stateSnap, rootId)
|
|
194
|
+
const effCfg = resolveWorkspaceConfig(stateSnap, rootId)
|
|
195
|
+
const permMode = normalizePermissionMode(effCfg.permissionMode, {
|
|
196
|
+
requireAck: true,
|
|
197
|
+
hasChiefRiskAck: hasValidChiefRiskAck(wsSnap),
|
|
198
|
+
})
|
|
199
|
+
const board = deps && deps.boardForSession && deps.boardFileFor
|
|
200
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
201
|
+
: null
|
|
202
|
+
|
|
203
|
+
const idFilter = Array.isArray(ids) && ids.length > 0 ? new Set(ids.map(String)) : null
|
|
204
|
+
const allPending = (wsSnap.suggestions || []).filter(s => s && s.status === 'pending' && (!idFilter || idFilter.has(s.id)))
|
|
205
|
+
if (!allPending.length) {
|
|
206
|
+
return {
|
|
207
|
+
ok: true,
|
|
208
|
+
executedCount: 0,
|
|
209
|
+
skippedGoalCount: 0,
|
|
210
|
+
blockedCount: 0,
|
|
211
|
+
failedCount: 0,
|
|
212
|
+
executed: [],
|
|
213
|
+
blocked: [],
|
|
214
|
+
skippedGoals: [],
|
|
215
|
+
summaries: ['当前没有待执行的参谋长建议。'],
|
|
216
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const executed = []
|
|
221
|
+
const blocked = []
|
|
222
|
+
const failed = []
|
|
223
|
+
const skippedGoals = []
|
|
224
|
+
const summaries = []
|
|
225
|
+
|
|
226
|
+
for (const sug of allPending) {
|
|
227
|
+
if (sug.kind === 'goal_approval' && !includeGoalApproval) {
|
|
228
|
+
skippedGoals.push({ id: sug.id, title: sug.title })
|
|
229
|
+
continue
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (sug.kind !== 'bound' && sug.kind !== 'goal_approval') {
|
|
233
|
+
const cmdSample = `${sug.draftText || ''}\n${sug.title || ''}`.trim()
|
|
234
|
+
const guardRes = evaluateSafetyGuardHardRules({
|
|
235
|
+
tool: 'relay',
|
|
236
|
+
opClass: 'workflow',
|
|
237
|
+
command: cmdSample,
|
|
238
|
+
args: { text: sug.draftText || '', title: sug.title || '' },
|
|
239
|
+
board,
|
|
240
|
+
})
|
|
241
|
+
if (guardRes.blocked) {
|
|
242
|
+
mutateChiefState((st) => {
|
|
243
|
+
const ws = ensureWorkspace(st, rootId)
|
|
244
|
+
const item = ws.suggestions.find(x => x && x.id === sug.id && x.status === 'pending')
|
|
245
|
+
if (item) item.status = 'dismissed'
|
|
246
|
+
pushAuditToWs(ws, {
|
|
247
|
+
mode: permMode,
|
|
248
|
+
stage: 'safety_guard',
|
|
249
|
+
decision: 'blocked',
|
|
250
|
+
operation: '批量执行参谋建议拦截',
|
|
251
|
+
target: clamp(sug.title, 80),
|
|
252
|
+
reason: guardRes.reason,
|
|
253
|
+
outcome: 'blocked',
|
|
254
|
+
by: 'operator',
|
|
255
|
+
}, rootId)
|
|
256
|
+
})
|
|
257
|
+
blocked.push({ id: sug.id, title: sug.title, reason: guardRes.reason })
|
|
258
|
+
summaries.push(`⛔ 已拦截建议「${clamp(sug.title, 36)}」:${guardRes.reason}`)
|
|
259
|
+
continue
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const res = await handleSuggestionDecision(deps, {
|
|
264
|
+
sessionId: rootId,
|
|
265
|
+
suggestionId: sug.id,
|
|
266
|
+
decision: 'approve',
|
|
267
|
+
pinGlobal: sug.kind === 'bound' && typeof pinGlobalDefault === 'boolean' ? pinGlobalDefault : undefined,
|
|
268
|
+
})
|
|
269
|
+
|
|
270
|
+
if (res && res.ok) {
|
|
271
|
+
executed.push({ id: sug.id, kind: sug.kind, title: sug.title, target: sug.targetLabel || sug.target })
|
|
272
|
+
if (res.boundApplied) {
|
|
273
|
+
summaries.push(`✅ 已应用边界「${res.boundApplied.label}」:${clamp(res.boundApplied.item, 44)}`)
|
|
274
|
+
} else if (res.goalApproved) {
|
|
275
|
+
summaries.push('✅ 已批准并结项当前核心目标')
|
|
276
|
+
} else if (res.delivery && res.delivery.target) {
|
|
277
|
+
summaries.push(`✅ 已采纳并递话给 @${res.delivery.target}:「${clamp(sug.title, 36)}」`)
|
|
278
|
+
} else {
|
|
279
|
+
summaries.push(`✅ 已执行建议:「${clamp(sug.title, 40)}」`)
|
|
280
|
+
}
|
|
281
|
+
} else {
|
|
282
|
+
const errMsg = (res && res.error) || '执行未完成'
|
|
283
|
+
failed.push({ id: sug.id, title: sug.title, error: errMsg })
|
|
284
|
+
summaries.push(`⚠️ 未完成「${clamp(sug.title, 36)}」:${errMsg}`)
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
mutateChiefState((st) => {
|
|
289
|
+
const ws = ensureWorkspace(st, rootId)
|
|
290
|
+
pushAuditToWs(ws, {
|
|
291
|
+
mode: permMode,
|
|
292
|
+
stage: 'executor',
|
|
293
|
+
decision: executed.length > 0 ? 'executed' : (blocked.length > 0 ? 'blocked' : 'noop'),
|
|
294
|
+
operation: '统一执行参谋建议',
|
|
295
|
+
target: `${executed.length} 项执行 / ${blocked.length} 项拦截 / ${skippedGoals.length} 项跳过`,
|
|
296
|
+
reason: clamp(summaries.slice(0, 3).join(';'), 200) || '批量执行建议',
|
|
297
|
+
outcome: blocked.length > 0 && executed.length === 0 ? 'blocked' : 'ok',
|
|
298
|
+
by: 'operator',
|
|
299
|
+
}, rootId)
|
|
300
|
+
if (executed.length > 0 || blocked.length > 0 || failed.length > 0) {
|
|
301
|
+
const header = `- 【📋 统一执行参谋建议回执】完成 ${executed.length} 项${blocked.length ? ` · 拦截 ${blocked.length} 项` : ''}${failed.length ? ` · 异常 ${failed.length} 项` : ''}${skippedGoals.length ? ` · 保留目标结项请示 ${skippedGoals.length} 项单独拍板` : ''}`
|
|
302
|
+
const actionTags = [`📋 执行建议 ×${executed.length}`]
|
|
303
|
+
if (blocked.length) actionTags.push(`🛡️ 红线拦截 ×${blocked.length}`)
|
|
304
|
+
ws.chat.push({
|
|
305
|
+
id: nextId('chat'),
|
|
306
|
+
role: 'chief',
|
|
307
|
+
kind: 'receipt',
|
|
308
|
+
text: [header, ...summaries.map(line => ` ${line}`)].join('\n'),
|
|
309
|
+
actions: actionTags,
|
|
310
|
+
at: Date.now(),
|
|
311
|
+
})
|
|
312
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
313
|
+
}
|
|
314
|
+
})
|
|
315
|
+
|
|
316
|
+
return {
|
|
317
|
+
ok: true,
|
|
318
|
+
executedCount: executed.length,
|
|
319
|
+
skippedGoalCount: skippedGoals.length,
|
|
320
|
+
blockedCount: blocked.length,
|
|
321
|
+
failedCount: failed.length,
|
|
322
|
+
executed,
|
|
323
|
+
blocked,
|
|
324
|
+
failed,
|
|
325
|
+
skippedGoals,
|
|
326
|
+
summaries,
|
|
327
|
+
view: await getChiefView(deps, rootId, { autoSummarize: executed.some(e => e.kind === 'bound') }),
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** 处理 L2 参谋模式逐项操作授权弹窗(拒绝 / 允许本次操作)。 */
|
|
332
|
+
export async function handleApprovalDecision(deps, {
|
|
333
|
+
sessionId = '',
|
|
334
|
+
approvalId = '',
|
|
335
|
+
decision = 'reject',
|
|
336
|
+
} = {}) {
|
|
337
|
+
const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : '') || String(sessionId || 'global')
|
|
338
|
+
let found = null
|
|
339
|
+
let currentMode = DEFAULT_CHIEF_PERMISSION_MODE
|
|
340
|
+
let existingNonPending = false
|
|
341
|
+
let hashMismatch = false
|
|
342
|
+
|
|
343
|
+
mutateChiefState((state) => {
|
|
344
|
+
const ws = ensureWorkspace(state, rootId)
|
|
345
|
+
const ackOk = hasValidChiefRiskAck(ws)
|
|
346
|
+
const eff = resolveWorkspaceConfig(state, rootId)
|
|
347
|
+
currentMode = normalizePermissionMode(eff.permissionMode, { requireAck: true, hasChiefRiskAck: ackOk })
|
|
348
|
+
const item = (ws.pendingApprovals || []).find(a => a && a.id === approvalId && a.status === 'pending')
|
|
349
|
+
if (!item) {
|
|
350
|
+
existingNonPending = (ws.pendingApprovals || []).some(a => a && a.id === approvalId)
|
|
351
|
+
pushAuditToWs(ws, {
|
|
352
|
+
mode: currentMode,
|
|
353
|
+
stage: 'permission_gate',
|
|
354
|
+
decision: existingNonPending ? 'replayed_approval' : 'invalid_approval_id',
|
|
355
|
+
operation: '伪造或重放审批拦截',
|
|
356
|
+
target: clamp(approvalId || '(empty)', 100),
|
|
357
|
+
reason: existingNonPending ? '该操作审批已处理完毕,拒绝重复提交或重放' : '未找到对应的 pending approvalId,拒绝执行',
|
|
358
|
+
outcome: 'rejected',
|
|
359
|
+
by: 'operator',
|
|
360
|
+
}, rootId)
|
|
361
|
+
return
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const expectedHash = computeApprovalPayloadHash(item.kind, item.payload || {})
|
|
365
|
+
if (decision === 'approve' && item.payloadHash && item.payloadHash !== expectedHash) {
|
|
366
|
+
hashMismatch = true
|
|
367
|
+
found = { ...item, payload: item.payload ? { ...item.payload } : {} }
|
|
368
|
+
item.status = 'failed'
|
|
369
|
+
item.resolvedAt = Date.now()
|
|
370
|
+
item.resolvedBy = 'safety_guard'
|
|
371
|
+
item.resultMessage = '审批载荷哈希校验失败(疑似载荷被篡改)'
|
|
372
|
+
if (item.resumeTaskId && Array.isArray(ws.resumeTasks)) {
|
|
373
|
+
const linkedTask = ws.resumeTasks.find(t => t && t.id === item.resumeTaskId)
|
|
374
|
+
if (linkedTask) {
|
|
375
|
+
linkedTask.status = 'failed'
|
|
376
|
+
linkedTask.resolvedAt = Date.now()
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
pushAuditToWs(ws, {
|
|
380
|
+
mode: currentMode,
|
|
381
|
+
stage: 'safety_guard',
|
|
382
|
+
decision: 'tampered_approval_payload',
|
|
383
|
+
operation: item.operationLabel,
|
|
384
|
+
target: item.targetLabel,
|
|
385
|
+
reason: 'approval payload SHA-256 校验失败,拒绝执行',
|
|
386
|
+
outcome: 'rejected',
|
|
387
|
+
by: 'safety_guard',
|
|
388
|
+
}, rootId)
|
|
389
|
+
ws.chat.push({
|
|
390
|
+
id: nextId('chat'),
|
|
391
|
+
role: 'chief',
|
|
392
|
+
kind: 'receipt',
|
|
393
|
+
text: `- 【🛡️ 审批载荷完整性校验失败】已拦截执行「${item.operationLabel} · \`${item.targetLabel}\`」(签名摘要不匹配)。`,
|
|
394
|
+
actions: ['🛡️ 载荷篡改拦截'],
|
|
395
|
+
at: Date.now(),
|
|
396
|
+
})
|
|
397
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
398
|
+
return
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
found = { ...item, payload: item.payload ? { ...item.payload } : {} }
|
|
402
|
+
if (decision !== 'approve') {
|
|
403
|
+
item.status = 'rejected'
|
|
404
|
+
item.resolvedAt = Date.now()
|
|
405
|
+
item.resolvedBy = 'operator'
|
|
406
|
+
item.resultMessage = '用户拒绝执行本次操作'
|
|
407
|
+
if (item.resumeTaskId && Array.isArray(ws.resumeTasks)) {
|
|
408
|
+
const linkedTask = ws.resumeTasks.find(t => t && t.id === item.resumeTaskId)
|
|
409
|
+
if (linkedTask) {
|
|
410
|
+
linkedTask.status = 'cancelled'
|
|
411
|
+
linkedTask.resolvedAt = Date.now()
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
pushAuditToWs(ws, {
|
|
415
|
+
mode: currentMode,
|
|
416
|
+
stage: 'permission_gate',
|
|
417
|
+
decision: 'rejected_by_user',
|
|
418
|
+
operation: item.operationLabel,
|
|
419
|
+
target: item.targetLabel,
|
|
420
|
+
reason: item.reason,
|
|
421
|
+
outcome: 'rejected',
|
|
422
|
+
by: 'operator',
|
|
423
|
+
}, rootId)
|
|
424
|
+
ws.chat.push({
|
|
425
|
+
id: nextId('chat'),
|
|
426
|
+
role: 'chief',
|
|
427
|
+
kind: 'receipt',
|
|
428
|
+
text: `- 【⛔ 已拒绝本次操作】${item.operationLabel} · \`${item.targetLabel}\``,
|
|
429
|
+
actions: ['⛔ 用户拒绝操作'],
|
|
430
|
+
at: Date.now(),
|
|
431
|
+
})
|
|
432
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
433
|
+
} else {
|
|
434
|
+
item.status = 'approved'
|
|
435
|
+
item.resolvedAt = Date.now()
|
|
436
|
+
item.resolvedBy = 'operator'
|
|
437
|
+
pushAuditToWs(ws, {
|
|
438
|
+
mode: currentMode,
|
|
439
|
+
stage: 'permission_gate',
|
|
440
|
+
decision: 'approved_by_user',
|
|
441
|
+
operation: item.operationLabel,
|
|
442
|
+
target: item.targetLabel,
|
|
443
|
+
reason: item.reason,
|
|
444
|
+
outcome: 'approved',
|
|
445
|
+
by: 'operator',
|
|
446
|
+
}, rootId)
|
|
447
|
+
}
|
|
448
|
+
})
|
|
449
|
+
|
|
450
|
+
if (!found) return { ok: false, error: existingNonPending ? '该操作授权已处理完毕,禁止重复放行' : '未找到该待确认操作或已处理完毕' }
|
|
451
|
+
if (hashMismatch) return { ok: false, tampered: true, error: '审批载荷哈希校验失败,已拒绝执行并写入安全审计' }
|
|
452
|
+
if (decision !== 'approve') {
|
|
453
|
+
return {
|
|
454
|
+
ok: true,
|
|
455
|
+
rejected: true,
|
|
456
|
+
approval: { ...found, status: 'rejected' },
|
|
457
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const board = deps && deps.boardForSession && deps.boardFileFor
|
|
462
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
463
|
+
: null
|
|
464
|
+
const payload = found.payload || {}
|
|
465
|
+
let execOk = false
|
|
466
|
+
let execRes = null
|
|
467
|
+
let resultMsg = ''
|
|
468
|
+
|
|
469
|
+
try {
|
|
470
|
+
if (found.kind === 'tool' && payload.tool) {
|
|
471
|
+
execRes = await executeChiefToolCall(deps, { tool: payload.tool, args: payload.args || {} }, {
|
|
472
|
+
rootId,
|
|
473
|
+
sessionId: payload.sessionId || rootId,
|
|
474
|
+
cwd: payload.cwd || resolveSessionWorkspaceCwd(deps, rootId),
|
|
475
|
+
permissionMode: currentMode === 'chief' ? 'chief' : 'strategist',
|
|
476
|
+
hasChiefRiskAck: currentMode === 'chief',
|
|
477
|
+
approvedOnce: true,
|
|
478
|
+
board,
|
|
479
|
+
upsertArchiveFn: buildChiefArchiveUpsertFn(deps, rootId),
|
|
480
|
+
compactNowFn: buildChiefCompactFn(deps, rootId),
|
|
481
|
+
recordAuditFn: (entry) => appendChiefAuditLog(rootId, entry),
|
|
482
|
+
by: 'operator(逐项授权)',
|
|
483
|
+
})
|
|
484
|
+
execOk = Boolean(execRes && execRes.ok)
|
|
485
|
+
resultMsg = execOk
|
|
486
|
+
? `已执行 ${found.operationLabel}(${found.targetLabel})`
|
|
487
|
+
: (execRes && execRes.error) || '执行未成功'
|
|
488
|
+
} else if (found.kind === 'relay') {
|
|
489
|
+
const guardRes = evaluateSafetyGuardHardRules({ tool: 'relay', opClass: 'workflow', command: payload.text || '', board })
|
|
490
|
+
if (guardRes.blocked) {
|
|
491
|
+
execOk = false
|
|
492
|
+
execRes = { ok: false, blockedBySafetyGuard: true, error: guardRes.reason }
|
|
493
|
+
resultMsg = guardRes.reason
|
|
494
|
+
appendChiefAuditLog(rootId, { mode: currentMode, stage: 'safety_guard', decision: 'blocked', operation: found.operationLabel, target: found.targetLabel, reason: guardRes.reason, outcome: 'blocked', by: 'operator' })
|
|
495
|
+
} else {
|
|
496
|
+
const deliv = await deliverCrossMessage(deps, {
|
|
497
|
+
fromSession: rootId,
|
|
498
|
+
fromLabel: payload.fromLabel || 'DSH 参谋 (逐项授权)',
|
|
499
|
+
target: payload.target || 'lead',
|
|
500
|
+
subject: payload.subject || '',
|
|
501
|
+
text: payload.text || '',
|
|
502
|
+
mode: payload.mode || 'steer',
|
|
503
|
+
imageBlocks: Array.isArray(payload.imageBlocks) ? payload.imageBlocks : [],
|
|
504
|
+
savedImagePaths: Array.isArray(payload.savedImagePaths) ? payload.savedImagePaths : [],
|
|
505
|
+
})
|
|
506
|
+
const isLeadTarget = /^(?:lead|main|主对话)$/i.test(String(payload.target || 'lead').trim())
|
|
507
|
+
if (isLeadTarget && (!deliv.ok || (payload.isBlankContext && !deliv.deliveredPhysical)) && deps && typeof deps.stagePendingTransfer === 'function') {
|
|
508
|
+
const staged = deps.stagePendingTransfer(
|
|
509
|
+
`[DSH 参谋预派发指令${payload.subject ? ' · ' + payload.subject : ''}]\n${payload.text || ''}`,
|
|
510
|
+
rootId,
|
|
511
|
+
{ by: 'chief', subject: payload.subject || '' },
|
|
512
|
+
)
|
|
513
|
+
if (staged) {
|
|
514
|
+
execOk = true
|
|
515
|
+
execRes = { ...deliv, ok: true, stagedPending: true, target: '主对话(待领)' }
|
|
516
|
+
resultMsg = '已暂存主对话待领交接指令'
|
|
517
|
+
} else {
|
|
518
|
+
execOk = Boolean(deliv && deliv.ok)
|
|
519
|
+
execRes = deliv
|
|
520
|
+
resultMsg = execOk ? `已投递给 ${deliv.target || found.targetLabel}` : ((deliv && deliv.error) || '投递失败')
|
|
521
|
+
}
|
|
522
|
+
} else {
|
|
523
|
+
execOk = Boolean(deliv && deliv.ok)
|
|
524
|
+
execRes = deliv
|
|
525
|
+
resultMsg = execOk ? `已投递给 ${deliv.target || found.targetLabel}` : ((deliv && deliv.error) || '投递失败')
|
|
526
|
+
}
|
|
527
|
+
appendChiefAuditLog(rootId, { mode: currentMode, stage: 'executor', decision: 'executed_approved', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'error', by: 'operator' })
|
|
528
|
+
}
|
|
529
|
+
} else if (found.kind === 'compact') {
|
|
530
|
+
const guardRes = evaluateSafetyGuardHardRules({ tool: 'session_compact', opClass: 'workflow', board })
|
|
531
|
+
if (guardRes.blocked) {
|
|
532
|
+
execOk = false
|
|
533
|
+
execRes = { ok: false, blockedBySafetyGuard: true, error: guardRes.reason }
|
|
534
|
+
resultMsg = guardRes.reason
|
|
535
|
+
} else {
|
|
536
|
+
execRes = await buildChiefCompactFn(deps, rootId)(payload.reason || found.reason)
|
|
537
|
+
execOk = Boolean(execRes && execRes.ok)
|
|
538
|
+
if (execOk && !execRes.noop) {
|
|
539
|
+
recordSmartCompactionChatReceipt(rootId, {
|
|
540
|
+
cRes: execRes,
|
|
541
|
+
ratioPct: Number(execRes.ratioPct) || 0,
|
|
542
|
+
via: '🛡️ 逐项授权压缩',
|
|
543
|
+
})
|
|
544
|
+
}
|
|
545
|
+
resultMsg = execOk
|
|
546
|
+
? (execRes.noop ? '已抢救细节入本会话档案柜(当前历史免压)' : '已抢救细节并完成主对话上下文静默压缩')
|
|
547
|
+
: ((execRes && execRes.error) || '压缩未完成')
|
|
548
|
+
appendChiefAuditLog(rootId, { mode: currentMode, stage: 'executor', decision: 'executed_approved', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'error', by: 'operator' })
|
|
549
|
+
}
|
|
550
|
+
} else if (found.kind === 'auto_continue') {
|
|
551
|
+
if (deps && typeof deps.triggerAutoContinueNow === 'function') {
|
|
552
|
+
execRes = await deps.triggerAutoContinueNow(payload.sessionId || rootId, payload.trigger || 'turn/end:approved', { detail: payload.detail || '' })
|
|
553
|
+
execOk = Boolean(execRes && execRes.ok)
|
|
554
|
+
resultMsg = execOk ? '已触发主对话断线续跑' : ((execRes && execRes.error) || '断线续跑未触发')
|
|
555
|
+
} else {
|
|
556
|
+
execOk = false
|
|
557
|
+
resultMsg = '当前宿主未提供续跑回调接口'
|
|
558
|
+
}
|
|
559
|
+
appendChiefAuditLog(rootId, { mode: currentMode, stage: 'executor', decision: 'executed_approved', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'error', by: 'operator' })
|
|
560
|
+
}
|
|
561
|
+
} catch (err) {
|
|
562
|
+
execOk = false
|
|
563
|
+
execRes = { ok: false, error: (err && err.message) || String(err || 'execution-failed') }
|
|
564
|
+
resultMsg = execRes.error
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
let updatedApproval = { ...found, status: execOk ? 'executed' : 'failed', resultMessage: resultMsg }
|
|
568
|
+
let resumeTaskToRun = null
|
|
569
|
+
mutateChiefState((state) => {
|
|
570
|
+
const ws = ensureWorkspace(state, rootId)
|
|
571
|
+
const item = (ws.pendingApprovals || []).find(a => a && a.id === approvalId)
|
|
572
|
+
if (item) {
|
|
573
|
+
item.status = execOk ? 'executed' : 'failed'
|
|
574
|
+
item.resultMessage = clamp(resultMsg, 260)
|
|
575
|
+
updatedApproval = { ...item }
|
|
576
|
+
}
|
|
577
|
+
ws.chat.push({
|
|
578
|
+
id: nextId('chat'),
|
|
579
|
+
role: 'chief',
|
|
580
|
+
kind: 'receipt',
|
|
581
|
+
...(found.resumeTaskId ? { resumeTaskId: found.resumeTaskId } : {}),
|
|
582
|
+
text: execOk
|
|
583
|
+
? `- 【✅ 已允许并执行】${found.operationLabel} · \`${found.targetLabel}\`\n 结果:${clamp(resultMsg, 240)}`
|
|
584
|
+
: `- 【⚠️ 授权操作未完成】${found.operationLabel} · \`${found.targetLabel}\`\n 说明:${clamp(resultMsg, 240)}`,
|
|
585
|
+
actions: [execOk ? '✅ 逐项授权执行' : '⚠️ 授权执行异常'],
|
|
586
|
+
at: Date.now(),
|
|
587
|
+
})
|
|
588
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
589
|
+
|
|
590
|
+
if (found.resumeTaskId && Array.isArray(ws.resumeTasks)) {
|
|
591
|
+
const task = ws.resumeTasks.find(t => t && t.id === found.resumeTaskId)
|
|
592
|
+
if (task) {
|
|
593
|
+
const doneSummary = `${found.operationLabel} (${found.targetLabel}): ${clamp(resultMsg, 140)}`
|
|
594
|
+
const updatedTask = upsertResumeTaskOnWs(ws, {
|
|
595
|
+
id: task.id,
|
|
596
|
+
appendCompletedAction: doneSummary,
|
|
597
|
+
})
|
|
598
|
+
const siblingPending = (ws.pendingApprovals || []).some(
|
|
599
|
+
a => a && a.id !== approvalId && a.resumeTaskId === task.id && a.status === 'pending',
|
|
600
|
+
)
|
|
601
|
+
if (!execOk) {
|
|
602
|
+
if (updatedTask) {
|
|
603
|
+
updatedTask.status = 'failed'
|
|
604
|
+
updatedTask.resolvedAt = Date.now()
|
|
605
|
+
}
|
|
606
|
+
} else if (!siblingPending && updatedTask) {
|
|
607
|
+
if (updatedTask.expiresAt && Date.now() > updatedTask.expiresAt) {
|
|
608
|
+
updatedTask.status = 'expired'
|
|
609
|
+
updatedTask.resolvedAt = Date.now()
|
|
610
|
+
} else if (found.kind === 'tool' && (updatedTask.resumeDepth || 0) < 2 && updatedTask.status !== 'resuming') {
|
|
611
|
+
updatedTask.status = 'resuming'
|
|
612
|
+
resumeTaskToRun = { ...updatedTask }
|
|
613
|
+
} else if (updatedTask.status === 'awaiting_approval') {
|
|
614
|
+
updatedTask.status = 'completed'
|
|
615
|
+
updatedTask.resolvedAt = Date.now()
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
})
|
|
621
|
+
|
|
622
|
+
let resumeOut = null
|
|
623
|
+
if (resumeTaskToRun) {
|
|
624
|
+
const execSummaryJson = (() => {
|
|
625
|
+
try { return JSON.stringify(execRes || {}).slice(0, 1000) } catch { return clamp(resultMsg, 400) }
|
|
626
|
+
})()
|
|
627
|
+
try {
|
|
628
|
+
resumeOut = await askOrCommandChief(deps, {
|
|
629
|
+
sessionId: rootId,
|
|
630
|
+
text: resumeTaskToRun.originalText,
|
|
631
|
+
forcedTarget: resumeTaskToRun.forcedTarget || '',
|
|
632
|
+
forcedMode: resumeTaskToRun.forcedMode || 'steer',
|
|
633
|
+
_resumeCtx: {
|
|
634
|
+
resumeTaskId: resumeTaskToRun.id,
|
|
635
|
+
resumeDepth: (resumeTaskToRun.resumeDepth || 0) + 1,
|
|
636
|
+
triggerKind: 'approval',
|
|
637
|
+
executedSummary: `${found.operationLabel} (${found.targetLabel}) => ${execSummaryJson}`,
|
|
638
|
+
savedImagePaths: resumeTaskToRun.savedImagePaths || [],
|
|
639
|
+
},
|
|
640
|
+
})
|
|
641
|
+
} catch (err) {
|
|
642
|
+
resumeOut = { ok: false, error: (err && err.message) || String(err || 'resume failed') }
|
|
643
|
+
}
|
|
644
|
+
mutateChiefState((st) => {
|
|
645
|
+
const ws = ensureWorkspace(st, rootId)
|
|
646
|
+
const task = (ws.resumeTasks || []).find(t => t && t.id === resumeTaskToRun.id)
|
|
647
|
+
if (task && task.status === 'resuming') {
|
|
648
|
+
task.status = resumeOut && resumeOut.ok !== false ? 'completed' : 'failed'
|
|
649
|
+
task.resolvedAt = Date.now()
|
|
650
|
+
}
|
|
651
|
+
})
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
const latestBoard = (resumeOut && resumeOut.board)
|
|
655
|
+
|| (deps && deps.boardForSession && deps.boardFileFor
|
|
656
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
657
|
+
: undefined)
|
|
658
|
+
return {
|
|
659
|
+
ok: true,
|
|
660
|
+
executed: execOk,
|
|
661
|
+
executionOk: execOk,
|
|
662
|
+
approval: updatedApproval,
|
|
663
|
+
result: execRes,
|
|
664
|
+
...(resumeOut ? { resumed: true, resumeTaskId: resumeTaskToRun.id, resumeReply: resumeOut.reply || '', resumePendingApprovals: resumeOut.pendingApprovals || [] } : {}),
|
|
665
|
+
...(latestBoard ? { board: latestBoard } : {}),
|
|
666
|
+
view: (resumeOut && resumeOut.view) || await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/** 处理模型/主代理提交的权限升级请求;若批准为最高档 L3 必须由后端校验 confirmedChiefRisk。 */
|
|
671
|
+
export async function handleElevationDecision(deps, {
|
|
672
|
+
sessionId = '',
|
|
673
|
+
elevationId = '',
|
|
674
|
+
decision = 'reject',
|
|
675
|
+
targetMode = '',
|
|
676
|
+
confirmedChiefRisk = false,
|
|
677
|
+
} = {}) {
|
|
678
|
+
const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : '') || String(sessionId || 'global')
|
|
679
|
+
const stateBefore = loadChiefState()
|
|
680
|
+
const wsBefore = ensureWorkspace(stateBefore, rootId)
|
|
681
|
+
const elev = wsBefore.pendingElevation
|
|
682
|
+
if (!elev || (elevationId && elev.id !== elevationId)) {
|
|
683
|
+
appendChiefAuditLog(rootId, {
|
|
684
|
+
mode: resolveWorkspaceConfig(stateBefore, rootId).permissionMode,
|
|
685
|
+
stage: 'permission_gate',
|
|
686
|
+
decision: 'invalid_elevation_id',
|
|
687
|
+
operation: '无效提权请求拦截',
|
|
688
|
+
target: clamp(elevationId || '(none)', 80),
|
|
689
|
+
reason: '当前没有匹配的可处理提权申请',
|
|
690
|
+
outcome: 'rejected',
|
|
691
|
+
by: 'operator',
|
|
692
|
+
})
|
|
693
|
+
return { ok: false, error: '当前没有待处理的提权申请' }
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
if (decision !== 'approve') {
|
|
697
|
+
mutateChiefState((s) => {
|
|
698
|
+
const ws = ensureWorkspace(s, rootId)
|
|
699
|
+
ws.pendingElevation = null
|
|
700
|
+
if (elev.resumeTaskId && Array.isArray(ws.resumeTasks)) {
|
|
701
|
+
const linkedTask = ws.resumeTasks.find(t => t && t.id === elev.resumeTaskId)
|
|
702
|
+
if (linkedTask) {
|
|
703
|
+
linkedTask.status = 'cancelled'
|
|
704
|
+
linkedTask.resolvedAt = Date.now()
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
pushAuditToWs(ws, {
|
|
708
|
+
mode: resolveWorkspaceConfig(s, rootId).permissionMode,
|
|
709
|
+
stage: 'permission_gate',
|
|
710
|
+
decision: 'elevation_rejected',
|
|
711
|
+
operation: '拒绝提权申请',
|
|
712
|
+
target: `${elev.fromMode} -> ${elev.targetMode}`,
|
|
713
|
+
reason: elev.reason,
|
|
714
|
+
outcome: 'rejected',
|
|
715
|
+
by: 'operator',
|
|
716
|
+
}, rootId)
|
|
717
|
+
ws.chat.push({
|
|
718
|
+
id: nextId('chat'),
|
|
719
|
+
role: 'chief',
|
|
720
|
+
kind: 'receipt',
|
|
721
|
+
text: `- 【🔒 已拒绝提权申请】维持当前权限,未升级至 ${CHIEF_PERMISSION_META[elev.targetMode]?.level || elev.targetMode}。`,
|
|
722
|
+
actions: ['🔒 拒绝提权'],
|
|
723
|
+
at: Date.now(),
|
|
724
|
+
})
|
|
725
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
726
|
+
})
|
|
727
|
+
return { ok: true, rejected: true, view: await getChiefView(deps, rootId, { autoSummarize: false }) }
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
const chosenMode = normalizePermissionMode(targetMode || elev.targetMode)
|
|
731
|
+
if (permissionRank(chosenMode) <= 0) {
|
|
732
|
+
return { ok: false, error: '无效的提权目标档位' }
|
|
733
|
+
}
|
|
734
|
+
if (chosenMode === 'chief' && confirmedChiefRisk !== true) {
|
|
735
|
+
appendChiefAuditLog(rootId, {
|
|
736
|
+
mode: resolveWorkspaceConfig(loadChiefState(), rootId).permissionMode,
|
|
737
|
+
stage: 'permission_gate',
|
|
738
|
+
decision: 'deny_unacknowledged_l3',
|
|
739
|
+
operation: 'L3 提权风险校验',
|
|
740
|
+
target: 'chief',
|
|
741
|
+
reason: '批准提权至最高档 L3 前必须勾选风险知悉确认',
|
|
742
|
+
outcome: 'denied',
|
|
743
|
+
by: 'operator',
|
|
744
|
+
})
|
|
745
|
+
return {
|
|
746
|
+
ok: false,
|
|
747
|
+
requireChiefRiskConfirm: true,
|
|
748
|
+
error: '提权至最高档「L3 · 参谋长模式」必须先阅读风险告知并勾选确认(confirmedChiefRisk: true)!',
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
const cfgRes = updateChiefConfig({
|
|
753
|
+
sessionId: rootId,
|
|
754
|
+
permissionMode: chosenMode,
|
|
755
|
+
confirmedChiefRisk: chosenMode === 'chief',
|
|
756
|
+
by: 'operator(提权审批)',
|
|
757
|
+
})
|
|
758
|
+
if (!cfgRes || cfgRes.ok === false) {
|
|
759
|
+
return cfgRes || { ok: false, error: '提权应用失败' }
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
let resumeTaskToRun = null
|
|
763
|
+
mutateChiefState((s) => {
|
|
764
|
+
const ws = ensureWorkspace(s, rootId)
|
|
765
|
+
ws.pendingElevation = null
|
|
766
|
+
pushAuditToWs(ws, {
|
|
767
|
+
mode: chosenMode,
|
|
768
|
+
stage: 'permission_gate',
|
|
769
|
+
decision: 'elevation_approved',
|
|
770
|
+
operation: '批准提权',
|
|
771
|
+
target: `${CHIEF_PERMISSION_META[elev.fromMode]?.level || elev.fromMode} -> ${CHIEF_PERMISSION_META[chosenMode].level}`,
|
|
772
|
+
reason: elev.reason,
|
|
773
|
+
outcome: 'approved',
|
|
774
|
+
by: 'operator',
|
|
775
|
+
}, rootId)
|
|
776
|
+
const meta = CHIEF_PERMISSION_META[chosenMode]
|
|
777
|
+
ws.chat.push({
|
|
778
|
+
id: nextId('chat'),
|
|
779
|
+
role: 'chief',
|
|
780
|
+
kind: 'receipt',
|
|
781
|
+
...(elev.resumeTaskId ? { resumeTaskId: elev.resumeTaskId } : {}),
|
|
782
|
+
text: `- 【🔐 已批准提权】当前会话权限已升级为「**${meta.level} · ${meta.title}**」${chosenMode === 'chief' ? '(已完成高风险确认)' : ''}。`,
|
|
783
|
+
actions: [`🔐 升至 ${meta.level}`],
|
|
784
|
+
at: Date.now(),
|
|
785
|
+
})
|
|
786
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
787
|
+
|
|
788
|
+
if (elev.resumeTaskId && Array.isArray(ws.resumeTasks)) {
|
|
789
|
+
const task = ws.resumeTasks.find(t => t && t.id === elev.resumeTaskId)
|
|
790
|
+
if (task) {
|
|
791
|
+
if (task.expiresAt && Date.now() > task.expiresAt) {
|
|
792
|
+
task.status = 'expired'
|
|
793
|
+
task.resolvedAt = Date.now()
|
|
794
|
+
} else if ((task.resumeDepth || 0) < 2 && task.status !== 'resuming') {
|
|
795
|
+
task.status = 'resuming'
|
|
796
|
+
resumeTaskToRun = { ...task }
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
})
|
|
801
|
+
|
|
802
|
+
let resumeOut = null
|
|
803
|
+
if (resumeTaskToRun) {
|
|
804
|
+
const meta = CHIEF_PERMISSION_META[chosenMode]
|
|
805
|
+
try {
|
|
806
|
+
resumeOut = await askOrCommandChief(deps, {
|
|
807
|
+
sessionId: rootId,
|
|
808
|
+
text: resumeTaskToRun.originalText,
|
|
809
|
+
forcedTarget: resumeTaskToRun.forcedTarget || '',
|
|
810
|
+
forcedMode: resumeTaskToRun.forcedMode || 'steer',
|
|
811
|
+
_resumeCtx: {
|
|
812
|
+
resumeTaskId: resumeTaskToRun.id,
|
|
813
|
+
resumeDepth: (resumeTaskToRun.resumeDepth || 0) + 1,
|
|
814
|
+
triggerKind: 'elevation',
|
|
815
|
+
executedSummary: `已批准提权至 ${meta.level} · ${meta.title}`,
|
|
816
|
+
savedImagePaths: resumeTaskToRun.savedImagePaths || [],
|
|
817
|
+
},
|
|
818
|
+
})
|
|
819
|
+
} catch (err) {
|
|
820
|
+
resumeOut = { ok: false, error: (err && err.message) || String(err || 'elevation resume failed') }
|
|
821
|
+
}
|
|
822
|
+
mutateChiefState((st) => {
|
|
823
|
+
const ws = ensureWorkspace(st, rootId)
|
|
824
|
+
const task = (ws.resumeTasks || []).find(t => t && t.id === resumeTaskToRun.id)
|
|
825
|
+
if (task && task.status === 'resuming') {
|
|
826
|
+
task.status = resumeOut && resumeOut.ok !== false ? 'completed' : 'failed'
|
|
827
|
+
task.resolvedAt = Date.now()
|
|
828
|
+
}
|
|
829
|
+
})
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
return {
|
|
833
|
+
ok: true,
|
|
834
|
+
approvedMode: chosenMode,
|
|
835
|
+
permissionMode: chosenMode,
|
|
836
|
+
config: cfgRes.config,
|
|
837
|
+
...(resumeOut ? { resumed: true, resumeTaskId: resumeTaskToRun.id, resumeReply: resumeOut.reply || '', pendingApprovals: resumeOut.pendingApprovals || [] } : {}),
|
|
838
|
+
...(resumeOut && resumeOut.board ? { board: resumeOut.board } : {}),
|
|
839
|
+
view: (resumeOut && resumeOut.view) || await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
840
|
+
}
|
|
841
|
+
}
|