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