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
package/chief-executor.js
CHANGED
|
@@ -2,32 +2,143 @@ import fs from 'node:fs'
|
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
import { spawn } from 'node:child_process'
|
|
4
4
|
|
|
5
|
-
export const CHIEF_PERMISSION_MODES = ['
|
|
6
|
-
export const DEFAULT_CHIEF_PERMISSION_MODE = '
|
|
5
|
+
export const CHIEF_PERMISSION_MODES = ['advisor', 'assistant', 'strategist', 'chief']
|
|
6
|
+
export const DEFAULT_CHIEF_PERMISSION_MODE = 'advisor'
|
|
7
7
|
|
|
8
|
-
export
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
export const CHIEF_PERMISSION_META = {
|
|
9
|
+
advisor: {
|
|
10
|
+
key: 'advisor',
|
|
11
|
+
rank: 0,
|
|
12
|
+
level: 'L0',
|
|
13
|
+
icon: '👁',
|
|
14
|
+
shortLabel: 'L0 顾问',
|
|
15
|
+
title: '顾问模式',
|
|
16
|
+
enTitle: 'READ ONLY',
|
|
17
|
+
badge: '默认模式',
|
|
18
|
+
tagline: '只观察、只分析、只建议。',
|
|
19
|
+
desc: 'L0 默认只读档:仅读取看板与允许访问的项目状态,分析任务并提建议,绝不修改工作区或任何工作流。',
|
|
20
|
+
bullets: [
|
|
21
|
+
'读取看板和允许访问的项目状态',
|
|
22
|
+
'分析任务、提供建议',
|
|
23
|
+
'不修改工作区',
|
|
24
|
+
'不修改主代理和子代理工作流',
|
|
25
|
+
],
|
|
26
|
+
},
|
|
27
|
+
assistant: {
|
|
28
|
+
key: 'assistant',
|
|
29
|
+
rank: 1,
|
|
30
|
+
level: 'L1',
|
|
31
|
+
icon: '🗂',
|
|
32
|
+
shortLabel: 'L1 助手',
|
|
33
|
+
title: '助手模式',
|
|
34
|
+
enTitle: 'ASSISTANT',
|
|
35
|
+
badge: '',
|
|
36
|
+
tagline: '允许自主维护参谋系统。',
|
|
37
|
+
desc: 'L1 参谋内务档:具备顾问全部能力,允许维护自身记忆、档案与看板配置,但不改工作区、不接管主子代理工作流。',
|
|
38
|
+
bullets: [
|
|
39
|
+
'顾问模式全部能力',
|
|
40
|
+
'管理自己的参谋系统',
|
|
41
|
+
'修改自己的记忆、档案和看板配置',
|
|
42
|
+
'不直接修改项目工作区',
|
|
43
|
+
'不接管主代理工作流',
|
|
44
|
+
],
|
|
45
|
+
},
|
|
46
|
+
strategist: {
|
|
47
|
+
key: 'strategist',
|
|
48
|
+
rank: 2,
|
|
49
|
+
level: 'L2',
|
|
50
|
+
icon: '🛡️',
|
|
51
|
+
shortLabel: 'L2 参谋',
|
|
52
|
+
title: '参谋模式',
|
|
53
|
+
enTitle: 'ADVISOR WITH APPROVAL',
|
|
54
|
+
badge: '逐项授权',
|
|
55
|
+
tagline: 'Agent 提出操作,用户决定是否执行。',
|
|
56
|
+
desc: 'L2 逐项确认档:可申请修改工作区文件、运行系统命令及调整主对话/子代理工作流,每项受控操作执行前均弹窗由您逐项确认。',
|
|
57
|
+
bullets: [
|
|
58
|
+
'助手模式全部能力',
|
|
59
|
+
'可以申请修改工作区文件',
|
|
60
|
+
'可以申请修改主对话和子代理工作流',
|
|
61
|
+
'每项受控操作执行前弹窗',
|
|
62
|
+
'用户确认后才能执行',
|
|
63
|
+
],
|
|
64
|
+
},
|
|
65
|
+
chief: {
|
|
66
|
+
key: 'chief',
|
|
67
|
+
rank: 3,
|
|
68
|
+
level: 'L3',
|
|
69
|
+
icon: '⚡',
|
|
70
|
+
shortLabel: 'L3 参谋长',
|
|
71
|
+
title: '参谋长模式',
|
|
72
|
+
enTitle: 'CHIEF OF STAFF',
|
|
73
|
+
badge: '主动风险知悉',
|
|
74
|
+
tagline: '用户明确接受更高自主权带来的操作风险。',
|
|
75
|
+
desc: 'L3 高权限自主档:可自主修改工作区、执行命令、切换主代理并协调子代理工作流;启用前必须阅读风险声明并主动勾选确认。',
|
|
76
|
+
bullets: [
|
|
77
|
+
'参谋模式全部能力',
|
|
78
|
+
'获得更高的自主执行权限',
|
|
79
|
+
'可以切换主代理',
|
|
80
|
+
'可以协调子代理及其工作流',
|
|
81
|
+
'启用前必须阅读风险声明并主动勾选确认',
|
|
82
|
+
],
|
|
83
|
+
},
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const PERM_ALIAS_MAP = {
|
|
87
|
+
advisor: 'advisor',
|
|
88
|
+
l0: 'advisor',
|
|
89
|
+
'read-only': 'advisor',
|
|
90
|
+
assistant: 'assistant',
|
|
91
|
+
l1: 'assistant',
|
|
92
|
+
strategist: 'strategist',
|
|
93
|
+
counselor: 'strategist',
|
|
94
|
+
l2: 'strategist',
|
|
95
|
+
'workspace-write': 'strategist',
|
|
96
|
+
'auto-review': 'strategist',
|
|
97
|
+
chief: 'chief',
|
|
98
|
+
'chief-of-staff': 'chief',
|
|
99
|
+
l3: 'chief',
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function normalizePermissionMode(raw, opts = {}) {
|
|
103
|
+
const v = String(raw || '').trim().toLowerCase()
|
|
104
|
+
const hasAck = Boolean(opts && opts.hasChiefRiskAck)
|
|
105
|
+
const requireAck = Boolean(opts && opts.requireAck)
|
|
106
|
+
if (v === 'danger-full-access') {
|
|
107
|
+
return hasAck ? 'chief' : DEFAULT_CHIEF_PERMISSION_MODE
|
|
108
|
+
}
|
|
109
|
+
const mapped = PERM_ALIAS_MAP[v] || DEFAULT_CHIEF_PERMISSION_MODE
|
|
110
|
+
if (mapped === 'chief' && requireAck && !hasAck) {
|
|
111
|
+
return DEFAULT_CHIEF_PERMISSION_MODE
|
|
112
|
+
}
|
|
113
|
+
return mapped
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function permissionRank(mode) {
|
|
117
|
+
const norm = normalizePermissionMode(mode)
|
|
118
|
+
return (CHIEF_PERMISSION_META[norm] && CHIEF_PERMISSION_META[norm].rank) ?? 0
|
|
11
119
|
}
|
|
12
120
|
|
|
13
121
|
export const CHIEF_TOOLS_PROMPT_GUIDE = [
|
|
14
|
-
'
|
|
15
|
-
'
|
|
16
|
-
'- `read_file`: `{ "path": "相对或绝对路径", "startLine": 1, "endLine": 180 }`',
|
|
17
|
-
'- `list_dir`: `{ "path": "可选目录路径,默认当前工作区" }`',
|
|
18
|
-
'- `search_files`: `{ "pattern": "正则或关键词", "path": "可选目录", "maxHits": 30 }`',
|
|
19
|
-
'- `
|
|
20
|
-
'- `
|
|
21
|
-
'- `
|
|
22
|
-
'- `
|
|
23
|
-
'- `
|
|
24
|
-
'- `
|
|
25
|
-
'- `
|
|
26
|
-
'- `
|
|
122
|
+
'【DSH 参谋系统实权工具协议(`toolCalls`)】',
|
|
123
|
+
'工具调用遵循统一安全架构:`用户模式 -> 操作请求 -> 安全卫兵硬性规则 -> 权限判定 -> 执行器 -> 审计日志`。不同档位权限边界不同:',
|
|
124
|
+
'- `read_file`: `{ "path": "相对或绝对路径", "startLine": 1, "endLine": 180 }` (L0+ 只读)',
|
|
125
|
+
'- `list_dir`: `{ "path": "可选目录路径,默认当前工作区" }` (L0+ 只读)',
|
|
126
|
+
'- `search_files`: `{ "pattern": "正则或关键词", "path": "可选目录", "maxHits": 30 }` (L0+ 只读)',
|
|
127
|
+
'- `archive_write`: `{ "vaultScope": "session|global", "folder": "coords|case|spec|ops|plan|inbox", "title": "标题", "summary": "摘要", "body": "正文", "tags": [] }` (需 L1 助手+)',
|
|
128
|
+
'- `write_file`: `{ "path": "文件路径", "content": "完整新文件内容", "reason": "修改原因" }` (L2 弹窗逐项确认 / L3 自主执行)',
|
|
129
|
+
'- `edit_file`: `{ "path": "文件路径", "target": "精确旧文本", "replacement": "精确新文本", "reason": "修改原因" }` (L2 弹窗逐项确认 / L3 自主执行)',
|
|
130
|
+
'- `run_command`: `{ "command": "终端命令", "cwd": "可选工作目录", "timeoutMs": 20000, "reason": "运行原因" }` (L2 弹窗逐项确认 / L3 自主执行)',
|
|
131
|
+
'- `main_agent_control`: `{ "op": "switch_model|steer|followup|interrupt", "modelRef": "switch_model时填写provider/model", "message": "steer/followup时填写指令", "reason": "调整主代理原因" }` (L2 弹窗逐项确认 / L3 自主执行)',
|
|
132
|
+
'- `subagent_dispatch`: `{ "taskId": "可选已有任务ID", "title": "无taskId时自动建卡标题", "agent": "子代理名", "prompt": "委派指令", "preset": "可选", "force": false, "reason": "派发原因" }` (L2 弹窗逐项确认 / L3 自主执行)',
|
|
133
|
+
'- `subagent_steer`: `{ "agent": "子代理名", "taskId": "可选", "message": "纠偏指令", "reason": "引导原因" }` (L2 弹窗逐项确认 / L3 自主执行)',
|
|
134
|
+
'- `subagent_interrupt`: `{ "agent": "子代理名", "taskId": "可选", "reason": "中断原因" }` (L2 弹窗逐项确认 / L3 自主执行)',
|
|
135
|
+
'- `session_compact`: `{ "reason": "触发原因" }` (L2 弹窗逐项确认 / L3 自主执行)',
|
|
136
|
+
'- `request_permission_elevation`: `{ "targetMode": "assistant|strategist|chief", "reason": "为何需要提权", "requestedActionSummary": "拟执行的具体受控操作简述" }` (L0+ 可随时向用户申请提权!)',
|
|
27
137
|
'注意:',
|
|
28
138
|
'1) 若需调用工具,请输出合法 JSON `{ "toolCalls": [...], "reply": "当前排查中的简要进度" }`。**严禁**输出 `<|DSML|...>`、`< | | DSML | | ...>`、`<|DSML|...>`、`<function_calls>` 或 `<invoke>` 等原生 XML 工具标记!',
|
|
29
|
-
'2)
|
|
30
|
-
'3)
|
|
139
|
+
'2) 若当前权限等级不足(如 L0 无法改看板/工作区、L1 无法改工作区或调度工作流),可先做只读分析,再调用 `request_permission_elevation`(或输出 JSON `"elevationRequest"`)写明申请目标档位与原因,由用户弹窗决定是否放行(申请 L3 参谋长模式将额外强制进行风险确认打勾)。若处于 L2 调用受控工具返回 `pendingApproval: true`,请如实告知用户已弹出「操作授权请求」弹窗等待点击「允许本次操作」,切勿重复调用同一工具!',
|
|
140
|
+
'3) **小白状态/步骤追问禁扫目录铁律**:当用户只是问「主对话现在在做什么」「处于什么步骤」「当前进度如何」「到哪一步了」「卡在哪」时,提示词中的【实时对话流现场快照】、【核心目标】与【小任务板/任务列表】已经包含完整状态,**严禁调用 `run_command` 或 `list_dir` 扫描本地磁盘目录**,请直接输出最终 JSON `{ "reply": "…" }` 用通俗人话回答!',
|
|
141
|
+
'4) 工具返回结果回传给你后,若已完成查验与执行,请输出最终 JSON(去掉 `"toolCalls"`),并在 `reply` 中以实测事实作答;任何权限或红线拦截时如实汇报,绝不伪造输出。',
|
|
31
142
|
].join('\n')
|
|
32
143
|
|
|
33
144
|
const DSML_PREFIX = '(?:[\\s||¦│┃]*DSML[\\s||¦│┃]*)'
|
|
@@ -97,6 +208,7 @@ export function parseDsmlToolCalls(rawText) {
|
|
|
97
208
|
const attrs = String(pm[2] || '')
|
|
98
209
|
let pVal = String(pm[3] || '').trim()
|
|
99
210
|
const isStr = /string\s*=\s*["']true["']/i.test(attrs)
|
|
211
|
+
|| (['content', 'text', 'target', 'replacement', 'body', 'command', 'cmd'].includes(pName) && !/string\s*=\s*["']false["']/i.test(attrs))
|
|
100
212
|
if (!isStr && (pVal.startsWith('{') || pVal.startsWith('[') || pVal === 'true' || pVal === 'false' || /^-?\d+(?:\.\d+)?$/.test(pVal))) {
|
|
101
213
|
try {
|
|
102
214
|
pVal = JSON.parse(pVal)
|
|
@@ -133,6 +245,12 @@ function clamp(text, maxLen = 200) {
|
|
|
133
245
|
return s.length > maxLen ? s.slice(0, maxLen) + '...' : s
|
|
134
246
|
}
|
|
135
247
|
|
|
248
|
+
function normalizeTextContent(value) {
|
|
249
|
+
if (typeof value === 'string') return value
|
|
250
|
+
if (value && typeof value === 'object') return JSON.stringify(value, null, 2)
|
|
251
|
+
return String(value ?? '')
|
|
252
|
+
}
|
|
253
|
+
|
|
136
254
|
function truncateMiddle(text, maxBytes = 12_288) {
|
|
137
255
|
const s = String(text || '')
|
|
138
256
|
if (s.length <= maxBytes) return s
|
|
@@ -165,44 +283,192 @@ export function isPathInsideWorkspace(workspaceRoot, targetPath) {
|
|
|
165
283
|
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
|
|
166
284
|
}
|
|
167
285
|
|
|
286
|
+
const SENSITIVE_CREDENTIAL_BASENAMES = /^(?:\.+env(?:\.[a-z0-9_-]+)?|\.credentials(?:\.[a-z0-9_-]+)?|\.(?:git-credentials|npmrc|pypirc|netrc))$/i
|
|
287
|
+
const SENSITIVE_CREDENTIAL_FULLPATH = /(?:id_rsa|id_ed25519|id_ecdsa|id_dsa|\.pem$|\.p12$|\.pfx$|credentials\.json$|secrets?\.(?:json|ya?ml)$)/i
|
|
288
|
+
|
|
289
|
+
function isSensitiveNameOrStream(candidate) {
|
|
290
|
+
const s = String(candidate || '').trim()
|
|
291
|
+
if (!s || s === '$DATA') return false
|
|
292
|
+
const slashNorm = s.replace(/\\/g, '/').toLowerCase()
|
|
293
|
+
const base = path.basename(slashNorm)
|
|
294
|
+
if (SENSITIVE_CREDENTIAL_BASENAMES.test(base)) return true
|
|
295
|
+
if (SENSITIVE_CREDENTIAL_FULLPATH.test(slashNorm)) return true
|
|
296
|
+
return false
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function resolveWithSymlinkTarget(filePath) {
|
|
300
|
+
const out = []
|
|
301
|
+
const raw = String(filePath || '').trim()
|
|
302
|
+
if (!raw) return out
|
|
303
|
+
out.push(raw)
|
|
304
|
+
try {
|
|
305
|
+
const abs = path.resolve(raw)
|
|
306
|
+
out.push(abs)
|
|
307
|
+
try {
|
|
308
|
+
const lst = fs.lstatSync(abs)
|
|
309
|
+
if (lst.isSymbolicLink()) {
|
|
310
|
+
const linkTarget = fs.readlinkSync(abs)
|
|
311
|
+
out.push(linkTarget)
|
|
312
|
+
out.push(path.resolve(path.dirname(abs), linkTarget))
|
|
313
|
+
}
|
|
314
|
+
} catch {}
|
|
315
|
+
out.push(safeRealpath(abs))
|
|
316
|
+
const parent = path.dirname(abs)
|
|
317
|
+
if (fs.existsSync(parent)) {
|
|
318
|
+
out.push(path.join(safeRealpath(parent), path.basename(abs)))
|
|
319
|
+
}
|
|
320
|
+
} catch {}
|
|
321
|
+
return out
|
|
322
|
+
}
|
|
323
|
+
|
|
168
324
|
function isSensitiveCredentialPath(filePath) {
|
|
169
|
-
const
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
325
|
+
const candidates = resolveWithSymlinkTarget(filePath)
|
|
326
|
+
for (const cand of candidates) {
|
|
327
|
+
if (isSensitiveNameOrStream(cand)) return true
|
|
328
|
+
// Strip Windows drive letter `C:` then inspect any NTFS Alternate Data Streams (`file.txt:.env:$DATA`)
|
|
329
|
+
const withoutDrive = String(cand || '').replace(/^[a-zA-Z]:(?=[\\/]|$)/, '')
|
|
330
|
+
if (withoutDrive.includes(':')) {
|
|
331
|
+
for (const streamPart of withoutDrive.split(':')) {
|
|
332
|
+
if (isSensitiveNameOrStream(streamPart)) return true
|
|
333
|
+
}
|
|
334
|
+
}
|
|
176
335
|
}
|
|
177
336
|
return false
|
|
178
337
|
}
|
|
179
338
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
339
|
+
function decodeEncodedPowerShell(command) {
|
|
340
|
+
const decodedParts = []
|
|
341
|
+
const raw = String(command || '')
|
|
342
|
+
const re = /(?:^|\s)-(?:e|ec|en|enc|enco|encod|encode|encoded|encodedc|encodedco|encodedcom|encodedcomm|encodedcomma|encodedcomman|encodedcommand)\s+([A-Za-z0-9+/=]{8,})/gi
|
|
343
|
+
let m
|
|
344
|
+
while ((m = re.exec(raw)) !== null) {
|
|
345
|
+
try {
|
|
346
|
+
const buf = Buffer.from(m[1], 'base64')
|
|
347
|
+
for (const enc of ['utf16le', 'utf8']) {
|
|
348
|
+
const rawTxt = buf.toString(enc)
|
|
349
|
+
if (/[\x00-\x08\x0e-\x1f\ufffd]/.test(rawTxt)) continue
|
|
350
|
+
const txt = rawTxt.trim()
|
|
351
|
+
if (txt.length >= 3 && /^[ -~\t\r\n\u4e00-\u9fff]+$/.test(txt)) {
|
|
352
|
+
decodedParts.push(txt)
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
} catch {}
|
|
356
|
+
}
|
|
357
|
+
return decodedParts.join(' ')
|
|
358
|
+
}
|
|
186
359
|
|
|
187
|
-
function
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
360
|
+
function extractCanonicalToolSubcommands(text) {
|
|
361
|
+
const extras = []
|
|
362
|
+
const s = String(text || '')
|
|
363
|
+
const gitValFlags = new Set(['-c', '--git-dir', '--work-tree', '--namespace', '--config-env', '--exec-path', '-p', '--paginate'])
|
|
364
|
+
const gitRe = /\bgit(?:\.exe)?\s+([^\n;|&`]+)/gi
|
|
365
|
+
let gm
|
|
366
|
+
while ((gm = gitRe.exec(s)) !== null) {
|
|
367
|
+
const tokens = gm[1].trim().split(/\s+/).filter(Boolean)
|
|
368
|
+
let i = 0
|
|
369
|
+
while (i < tokens.length) {
|
|
370
|
+
const tok = tokens[i]
|
|
371
|
+
if (tok === '-C' || gitValFlags.has(tok)) {
|
|
372
|
+
i += 2
|
|
373
|
+
continue
|
|
374
|
+
}
|
|
375
|
+
if (tok.startsWith('-')) {
|
|
376
|
+
i += 1
|
|
377
|
+
continue
|
|
378
|
+
}
|
|
379
|
+
break
|
|
380
|
+
}
|
|
381
|
+
if (i < tokens.length) {
|
|
382
|
+
const rest = tokens.slice(i).join(' ')
|
|
383
|
+
extras.push(`git ${tokens[i]}`, `git ${rest}`)
|
|
384
|
+
}
|
|
192
385
|
}
|
|
193
|
-
|
|
386
|
+
const npmRe = /\bnpm(?:\.cmd|\.exe)?\s+([^\n;|&`]+)/gi
|
|
387
|
+
let nm
|
|
388
|
+
while ((nm = npmRe.exec(s)) !== null) {
|
|
389
|
+
const tokens = nm[1].trim().split(/\s+/).filter(Boolean)
|
|
390
|
+
let i = 0
|
|
391
|
+
while (i < tokens.length && tokens[i].startsWith('-')) {
|
|
392
|
+
i += (tokens[i] === '--registry' || tokens[i] === '--tag' || tokens[i] === '--prefix') ? 2 : 1
|
|
393
|
+
}
|
|
394
|
+
if (i < tokens.length) {
|
|
395
|
+
extras.push(`npm ${tokens.slice(i).join(' ')}`)
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
return extras.join(' ')
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
export function normalizeCommandForSecurity(command) {
|
|
402
|
+
const nfkc = String(command || '').normalize('NFKC')
|
|
403
|
+
if (!nfkc) return ''
|
|
404
|
+
const psDecoded = decodeEncodedPowerShell(nfkc)
|
|
405
|
+
const base = psDecoded ? `${nfkc} ${psDecoded}` : nfkc
|
|
406
|
+
const concatCollapsed = base.replace(/(['"`])\s*\+\s*\1/g, '')
|
|
407
|
+
const escapedQuotesUnwrapped = concatCollapsed.replace(/\\(["'`])/g, '$1').replace(/["'`]/g, '')
|
|
408
|
+
const caretCollapsed = escapedQuotesUnwrapped.replace(/\^([a-zA-Z0-9_.-])/g, '$1')
|
|
409
|
+
const quoteStripped = concatCollapsed.replace(/["'`]/g, '')
|
|
410
|
+
const shellUnescaped = caretCollapsed.replace(/\\([ \t!$&()*,.;<>?@[\]^`{|}~])/g, '$1')
|
|
411
|
+
const spaceCollapsed = shellUnescaped.replace(/\s+/g, ' ').trim()
|
|
412
|
+
const canonicalTools = [
|
|
413
|
+
extractCanonicalToolSubcommands(spaceCollapsed),
|
|
414
|
+
extractCanonicalToolSubcommands(caretCollapsed.replace(/\s+/g, ' ').trim()),
|
|
415
|
+
].filter(Boolean).join(' ')
|
|
416
|
+
return [nfkc, psDecoded, concatCollapsed, quoteStripped, escapedQuotesUnwrapped, caretCollapsed, spaceCollapsed, canonicalTools]
|
|
417
|
+
.filter(Boolean)
|
|
418
|
+
.join(' \n ')
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const DESTRUCTIVE_COMMAND_PATTERNS = [
|
|
422
|
+
/\brm\s+-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*\s+(?:\/(?:etc|usr|bin|sbin|var|lib|boot|dev|proc|sys|root|home|\*)?(?=$|[\s/])|~|\*|\.\.)/i,
|
|
423
|
+
/\bgit\s+(?:reset\s+--hard|clean\s+-[a-z]*f[a-z]*d|push\s+(?:--force|-f)\b)/i,
|
|
424
|
+
/\b(?:format|diskpart|cipher\s+\/w|bcdedit)\b/i,
|
|
425
|
+
/\bdel\s+\/[fqs][^\n]*[a-z]:\\/i,
|
|
426
|
+
/\bRemove-Item\b[^\n]*-Recurse[^\n]*-Force[^\n]*(?:[a-z]:\\|\*)/i,
|
|
427
|
+
/\b(?:shutdown(?:\.exe)?|restart-computer|stop-computer|mkfs|dd\s+if=.*of=\/dev\/)\b/i,
|
|
428
|
+
/\breg(?:\.exe)?\s+delete\s+(?:hklm|hkcr|hkcu\\software\\microsoft)\b/i,
|
|
429
|
+
/\bdrop\s+(?:database|schema)\b/i,
|
|
430
|
+
]
|
|
431
|
+
|
|
432
|
+
function isDestructiveShellCommand(command) {
|
|
433
|
+
const raw = String(command || '').trim()
|
|
434
|
+
if (!raw) return false
|
|
435
|
+
const norm = normalizeCommandForSecurity(raw)
|
|
436
|
+
return DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(raw) || re.test(norm))
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function commandTouchesSensitiveCredential(command) {
|
|
440
|
+
const raw = String(command || '')
|
|
441
|
+
if (!raw.trim()) return false
|
|
442
|
+
const norm = normalizeCommandForSecurity(raw)
|
|
443
|
+
const varExpanded = norm
|
|
444
|
+
.replace(/%[A-Za-z0-9_]+%/g, '/')
|
|
445
|
+
.replace(/\$env:[A-Za-z0-9_]+/gi, '/')
|
|
446
|
+
.replace(/\$\{[A-Za-z0-9_]+\}/g, '/')
|
|
447
|
+
const re = /(?:^|[\s"'=/\\:;>|&])(?:\.+env(?:\.[a-z0-9_-]+)?|\.credentials(?:\.[a-z0-9_-]+)?|\.(?:git-credentials|npmrc|pypirc|netrc)|id_rsa|id_ed25519|id_ecdsa|id_dsa|[a-z0-9_.-]+\.(?:pem|p12|pfx))(?:$|[\s"';&|><)\r\n])/i
|
|
448
|
+
return re.test(raw) || re.test(norm) || re.test(varExpanded)
|
|
194
449
|
}
|
|
195
450
|
|
|
196
451
|
/**
|
|
197
452
|
* 无论当前处于何种权限级别(包括 danger-full-access),都坚决守住用户在看板中设定的禁止红线。
|
|
198
453
|
*/
|
|
199
|
-
export function checkForbiddenBounds(board, actionDesc = '', commandOrPath = '') {
|
|
454
|
+
export function checkForbiddenBounds(board, actionDesc = '', commandOrPath = '', extraContent = '') {
|
|
200
455
|
const forbidden = [
|
|
201
456
|
...((board && board.bounds && Array.isArray(board.bounds.forbidden)) ? board.bounds.forbidden : []),
|
|
202
457
|
...((board && board.pinnedBounds && Array.isArray(board.pinnedBounds.forbidden)) ? board.pinnedBounds.forbidden : []),
|
|
203
458
|
]
|
|
204
459
|
if (!forbidden.length) return { blocked: false }
|
|
205
|
-
const
|
|
460
|
+
const primary = String(commandOrPath || '')
|
|
461
|
+
const normCmd = normalizeCommandForSecurity(primary)
|
|
462
|
+
const contentSample = String(extraContent || '').slice(0, 8192).normalize('NFKC')
|
|
463
|
+
const haystack = [
|
|
464
|
+
String(actionDesc || ''),
|
|
465
|
+
primary,
|
|
466
|
+
primary.replace(/\\/g, '/'),
|
|
467
|
+
normCmd,
|
|
468
|
+
normCmd.replace(/\\/g, '/'),
|
|
469
|
+
contentSample,
|
|
470
|
+
contentSample.replace(/\\/g, '/'),
|
|
471
|
+
].join(' \n ').toLowerCase()
|
|
206
472
|
|
|
207
473
|
for (const rule of forbidden) {
|
|
208
474
|
const rText = String(rule || '').trim()
|
|
@@ -406,45 +672,453 @@ function runRgSearch(rootDir, pattern, maxHits = 30) {
|
|
|
406
672
|
})
|
|
407
673
|
}
|
|
408
674
|
|
|
409
|
-
|
|
675
|
+
export function getToolOpClass(tool) {
|
|
676
|
+
switch (String(tool || '').trim()) {
|
|
677
|
+
case 'read_file':
|
|
678
|
+
case 'list_dir':
|
|
679
|
+
case 'search_files':
|
|
680
|
+
return 'read'
|
|
681
|
+
case 'request_permission_elevation':
|
|
682
|
+
return 'elevation_request'
|
|
683
|
+
case 'archive_write':
|
|
684
|
+
return 'chief_system'
|
|
685
|
+
case 'write_file':
|
|
686
|
+
case 'edit_file':
|
|
687
|
+
case 'run_command':
|
|
688
|
+
return 'workspace'
|
|
689
|
+
case 'subagent_dispatch':
|
|
690
|
+
case 'subagent_steer':
|
|
691
|
+
case 'subagent_interrupt':
|
|
692
|
+
case 'main_agent_control':
|
|
693
|
+
case 'session_compact':
|
|
694
|
+
return 'workflow'
|
|
695
|
+
default:
|
|
696
|
+
return 'workflow'
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** 安全卫兵硬性规则:优先于四级权限判定,L3 与逐项放行均不可绕过。 */
|
|
701
|
+
export function evaluateSafetyGuardHardRules({
|
|
702
|
+
tool = '',
|
|
703
|
+
opClass = '',
|
|
704
|
+
targetPath = '',
|
|
705
|
+
command = '',
|
|
706
|
+
content = '',
|
|
707
|
+
target = '',
|
|
708
|
+
replacement = '',
|
|
709
|
+
extraContent = '',
|
|
710
|
+
args = null,
|
|
711
|
+
board = null,
|
|
712
|
+
} = {}) {
|
|
713
|
+
const argObj = args && typeof args === 'object' ? args : {}
|
|
714
|
+
const resolvedPath = targetPath || (typeof argObj.path === 'string' ? argObj.path : '')
|
|
715
|
+
const resolvedCommand = command || (typeof argObj.command === 'string' ? argObj.command : (typeof argObj.cmd === 'string' ? argObj.cmd : ''))
|
|
716
|
+
|
|
717
|
+
if (resolvedPath && isSensitiveCredentialPath(resolvedPath)) {
|
|
718
|
+
return {
|
|
719
|
+
blocked: true,
|
|
720
|
+
stage: 'safety_guard',
|
|
721
|
+
rule: 'sensitive_credential',
|
|
722
|
+
reason: `安全卫兵拦截访问敏感凭据文件:${path.basename(resolvedPath)}`,
|
|
723
|
+
badge: '🛡️ 卫兵拦凭据',
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
if (resolvedCommand && commandTouchesSensitiveCredential(resolvedCommand)) {
|
|
727
|
+
return {
|
|
728
|
+
blocked: true,
|
|
729
|
+
stage: 'safety_guard',
|
|
730
|
+
rule: 'sensitive_credential_cmd',
|
|
731
|
+
reason: '安全卫兵拦截触及敏感凭据路径(.env / .credentials / 私钥证书)的终端命令',
|
|
732
|
+
badge: '🛡️ 卫兵拦凭据命令',
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
if (resolvedCommand && isDestructiveShellCommand(resolvedCommand)) {
|
|
736
|
+
return {
|
|
737
|
+
blocked: true,
|
|
738
|
+
stage: 'safety_guard',
|
|
739
|
+
rule: 'destructive_command',
|
|
740
|
+
reason: `安全卫兵拦截高危毁灭性系统命令:${clamp(resolvedCommand, 80)}`,
|
|
741
|
+
badge: '🛡️ 卫兵拦高危命令',
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
if (opClass !== 'read' && opClass !== 'elevation_request') {
|
|
745
|
+
const checkInput = resolvedPath || resolvedCommand
|
|
746
|
+
const payloadParts = [
|
|
747
|
+
content,
|
|
748
|
+
target,
|
|
749
|
+
replacement,
|
|
750
|
+
extraContent,
|
|
751
|
+
argObj.content,
|
|
752
|
+
argObj.target,
|
|
753
|
+
argObj.replacement,
|
|
754
|
+
argObj.prompt,
|
|
755
|
+
argObj.message,
|
|
756
|
+
argObj.text,
|
|
757
|
+
argObj.body,
|
|
758
|
+
]
|
|
759
|
+
.filter(v => v !== undefined && v !== null && String(v).trim())
|
|
760
|
+
.map(v => String(v).slice(0, 8192))
|
|
761
|
+
const mergedExtra = payloadParts.join('\n').slice(0, 12_288)
|
|
762
|
+
const boundCheck = checkForbiddenBounds(board, tool, checkInput, mergedExtra)
|
|
763
|
+
if (boundCheck.blocked) {
|
|
764
|
+
return {
|
|
765
|
+
blocked: true,
|
|
766
|
+
stage: 'safety_guard',
|
|
767
|
+
rule: 'forbidden_bound',
|
|
768
|
+
matchedRule: boundCheck.matchedRule,
|
|
769
|
+
reason: `安全卫兵命中禁止红线【${boundCheck.matchedRule}】,坚决拦截:${clamp(checkInput || tool, 80)}`,
|
|
770
|
+
badge: '🛡️ 卫兵拦红线',
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
return { blocked: false }
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** 四级权限门禁判定:advisor(L0) / assistant(L1) / strategist(L2) / chief(L3)。 */
|
|
778
|
+
export function evaluateChiefPermissionGate({
|
|
779
|
+
permissionMode = DEFAULT_CHIEF_PERMISSION_MODE,
|
|
780
|
+
hasChiefRiskAck = false,
|
|
781
|
+
opClass = 'read',
|
|
782
|
+
tool = '',
|
|
783
|
+
approvedOnce = false,
|
|
784
|
+
} = {}) {
|
|
785
|
+
const mode = normalizePermissionMode(permissionMode, { requireAck: true, hasChiefRiskAck })
|
|
786
|
+
const meta = CHIEF_PERMISSION_META[mode] || CHIEF_PERMISSION_META.advisor
|
|
787
|
+
|
|
788
|
+
if (opClass === 'read' || opClass === 'elevation_request') {
|
|
789
|
+
return { decision: 'allow', mode }
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
if (opClass === 'chief_system') {
|
|
793
|
+
if (mode === 'advisor') {
|
|
794
|
+
return {
|
|
795
|
+
decision: 'deny_mode',
|
|
796
|
+
mode,
|
|
797
|
+
requiredMode: 'assistant',
|
|
798
|
+
error: '当前处于「L0 · 顾问模式(只读)」,仅允许分析与建议,不能修改参谋记忆、档案或看板配置。可向用户申请提权至「L1 · 助手模式」。',
|
|
799
|
+
badge: '🔒 L0禁改参谋系统',
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
return { decision: 'allow', mode }
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// 'workspace' or 'workflow'
|
|
806
|
+
if (mode === 'advisor' || mode === 'assistant') {
|
|
807
|
+
const targetDesc = opClass === 'workspace' ? '修改项目工作区或执行系统命令' : '调整主对话及子代理工作流'
|
|
808
|
+
return {
|
|
809
|
+
decision: 'deny_mode',
|
|
810
|
+
mode,
|
|
811
|
+
requiredMode: 'strategist',
|
|
812
|
+
error: `当前处于「${meta.level} · ${meta.title}」,禁止${targetDesc}(${tool})。如需执行,请向用户申请提权至「L2 · 参谋模式(逐项授权)」或「L3 · 参谋长模式」。`,
|
|
813
|
+
badge: `🔒 ${meta.level}禁止操作`,
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
if (mode === 'strategist') {
|
|
818
|
+
if (approvedOnce) {
|
|
819
|
+
return { decision: 'allow_approved', mode }
|
|
820
|
+
}
|
|
821
|
+
return {
|
|
822
|
+
decision: 'require_approval',
|
|
823
|
+
mode,
|
|
824
|
+
requiredMode: 'strategist',
|
|
825
|
+
error: '「L2 · 参谋模式」要求先通过操作授权弹窗由用户逐项确认。',
|
|
826
|
+
badge: '🛡️ 待逐项确认',
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
// mode === 'chief'
|
|
831
|
+
if (!hasChiefRiskAck) {
|
|
832
|
+
return {
|
|
833
|
+
decision: 'deny_unacknowledged_l3',
|
|
834
|
+
mode: 'advisor',
|
|
835
|
+
requiredMode: 'chief',
|
|
836
|
+
error: '未检测到「L3 · 参谋长模式」风险知悉确认状态(chiefRiskAck),后端拒绝高权限自主执行。',
|
|
837
|
+
badge: '🛡️ L3未授权拦截',
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
return { decision: 'allow', mode: 'chief' }
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
function displayRelTarget(cwd, rawTarget) {
|
|
844
|
+
const raw = String(rawTarget || '').trim()
|
|
845
|
+
if (!raw) return '工作区'
|
|
846
|
+
const abs = path.resolve(cwd || process.cwd(), raw)
|
|
847
|
+
if (cwd && isPathInsideWorkspace(cwd, abs)) {
|
|
848
|
+
const rel = path.relative(safeRealpath(cwd), safeRealpath(abs))
|
|
849
|
+
return (rel || path.basename(abs) || '.').replace(/\\/g, '/')
|
|
850
|
+
}
|
|
851
|
+
return abs
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/** 为 L2 参谋模式逐项授权弹窗生成清晰人类可读的 操作 / 目标 / 原因 / 影响。 */
|
|
855
|
+
export function describeControlledOperationMeta(tool, args = {}, cwd = '') {
|
|
856
|
+
const reasonArg = clamp(args.reason || args.rationale || args.subject || '', 140)
|
|
857
|
+
const relPath = args.path ? displayRelTarget(cwd, args.path) : ''
|
|
858
|
+
const baseName = relPath ? path.basename(relPath).toLowerCase() : ''
|
|
859
|
+
|
|
860
|
+
switch (tool) {
|
|
861
|
+
case 'edit_file':
|
|
862
|
+
return {
|
|
863
|
+
category: 'workspace_file',
|
|
864
|
+
operationLabel: '修改工作区文件',
|
|
865
|
+
targetLabel: relPath || '指定文件',
|
|
866
|
+
reason: reasonArg || 'Agent 请求更新该文件内容',
|
|
867
|
+
impact: baseName === 'package.json' ? '可能改变项目依赖关系或构建脚本' : '将局部修改项目源码或配置文件',
|
|
868
|
+
preview: args.target ? `替换片段:${clamp(args.target, 100)} -> ${clamp(args.replacement || '', 100)}` : '',
|
|
869
|
+
}
|
|
870
|
+
case 'write_file': {
|
|
871
|
+
const exists = args.path && fs.existsSync(path.resolve(cwd || process.cwd(), String(args.path)))
|
|
872
|
+
const previewText = normalizeTextContent(args.content)
|
|
873
|
+
return {
|
|
874
|
+
category: 'workspace_file',
|
|
875
|
+
operationLabel: exists ? '覆盖写入工作区文件' : '新建工作区文件',
|
|
876
|
+
targetLabel: relPath || '新文件',
|
|
877
|
+
reason: reasonArg || 'Agent 请求写入工作区文件',
|
|
878
|
+
impact: baseName === 'package.json'
|
|
879
|
+
? '可能改变项目依赖关系或构建脚本'
|
|
880
|
+
: (exists ? '将覆盖目标文件现有全部内容' : '将在项目工作区创建新文件'),
|
|
881
|
+
preview: previewText ? `写入内容 (${Buffer.byteLength(previewText, 'utf8')} 字节):${clamp(previewText, 110)}` : '',
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
case 'run_command': {
|
|
885
|
+
const cmd = String(args.command || args.cmd || '').trim()
|
|
886
|
+
return {
|
|
887
|
+
category: 'system_command',
|
|
888
|
+
operationLabel: '执行系统命令',
|
|
889
|
+
targetLabel: clamp(cmd || '终端命令', 90),
|
|
890
|
+
reason: reasonArg || 'Agent 请求在工作区运行终端命令',
|
|
891
|
+
impact: /(?:npm|pnpm|yarn)\s+(?:i|install|add|remove|uninstall)\b/i.test(cmd)
|
|
892
|
+
? '可能安装或变更项目依赖包'
|
|
893
|
+
: '将在本机工作目录启动子进程并可能改变文件状态',
|
|
894
|
+
preview: args.cwd ? `执行目录:${displayRelTarget(cwd, args.cwd)}` : '',
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
case 'main_agent_control': {
|
|
898
|
+
const op = String(args.op || 'steer').trim()
|
|
899
|
+
const opTitle = op === 'switch_model'
|
|
900
|
+
? '切换主代理模型'
|
|
901
|
+
: op === 'interrupt'
|
|
902
|
+
? '中断主代理当前回合'
|
|
903
|
+
: '调整主对话工作流'
|
|
904
|
+
const target = op === 'switch_model'
|
|
905
|
+
? (args.modelRef || args.model || '主对话模型')
|
|
906
|
+
: '主对话 (@lead)'
|
|
907
|
+
return {
|
|
908
|
+
category: 'main_workflow',
|
|
909
|
+
operationLabel: opTitle,
|
|
910
|
+
targetLabel: String(target),
|
|
911
|
+
reason: reasonArg || clamp(args.message || '参谋请求调整主对话执行', 120),
|
|
912
|
+
impact: op === 'switch_model'
|
|
913
|
+
? '将改变主对话后续轮次所使用的底层大模型'
|
|
914
|
+
: '将直接影响主对话当前执行节奏与工作流状态',
|
|
915
|
+
preview: args.message ? clamp(args.message, 140) : '',
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
case 'subagent_dispatch':
|
|
919
|
+
return {
|
|
920
|
+
category: 'subagent_workflow',
|
|
921
|
+
operationLabel: '派发子代理工作流',
|
|
922
|
+
targetLabel: '@' + String(args.agent || args.subagent || '新子代理'),
|
|
923
|
+
reason: reasonArg || clamp(args.title || args.prompt || '请求调度子代理协同处理任务', 120),
|
|
924
|
+
impact: '将创建或唤醒子代理并向其下发任务提示词',
|
|
925
|
+
preview: clamp(args.prompt || args.message || '', 140),
|
|
926
|
+
}
|
|
927
|
+
case 'subagent_steer':
|
|
928
|
+
return {
|
|
929
|
+
category: 'subagent_workflow',
|
|
930
|
+
operationLabel: '引导子代理工作流',
|
|
931
|
+
targetLabel: '@' + String(args.agent || args.target || '子代理'),
|
|
932
|
+
reason: reasonArg || clamp(args.message || '请求向运行中的子代理插话纠偏', 120),
|
|
933
|
+
impact: '将实时向子代理注入纠偏指令并改变其下一步行动',
|
|
934
|
+
preview: clamp(args.message || '', 140),
|
|
935
|
+
}
|
|
936
|
+
case 'subagent_interrupt':
|
|
937
|
+
return {
|
|
938
|
+
category: 'subagent_workflow',
|
|
939
|
+
operationLabel: '中断子代理工作流',
|
|
940
|
+
targetLabel: '@' + String(args.agent || args.target || '子代理'),
|
|
941
|
+
reason: reasonArg || '请求立即中断子代理当前执行',
|
|
942
|
+
impact: '将强行中止目标子代理正在运行的回合',
|
|
943
|
+
preview: '',
|
|
944
|
+
}
|
|
945
|
+
case 'session_compact':
|
|
946
|
+
return {
|
|
947
|
+
category: 'main_workflow',
|
|
948
|
+
operationLabel: '压缩主对话上下文 (/compact)',
|
|
949
|
+
targetLabel: '当前主会话',
|
|
950
|
+
reason: reasonArg || '压缩历史上下文前将先抢救摘要入档案柜',
|
|
951
|
+
impact: '会触发主会话历史压缩,减少上下文占用并重置部分窗口细节',
|
|
952
|
+
preview: '',
|
|
953
|
+
}
|
|
954
|
+
default:
|
|
955
|
+
return {
|
|
956
|
+
category: 'workspace_file',
|
|
957
|
+
operationLabel: `执行受控操作 (${tool})`,
|
|
958
|
+
targetLabel: relPath || '当前会话',
|
|
959
|
+
reason: reasonArg || 'Agent 申请执行受控操作',
|
|
960
|
+
impact: '将对当前工作区或对话工作流产生变更',
|
|
961
|
+
preview: '',
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
/**
|
|
967
|
+
* 统一六段执行管线入口:
|
|
968
|
+
* 用户模式 -> 操作请求 -> 安全卫兵硬性规则 -> 权限判定 -> 执行器 -> 审计日志
|
|
969
|
+
*/
|
|
410
970
|
export async function executeChiefToolCall(deps, call, execCtx = {}) {
|
|
411
971
|
const tool = String(call && (call.tool || call.name) || '').trim()
|
|
412
972
|
const args = (call && call.args && typeof call.args === 'object') ? call.args : (call && typeof call === 'object' ? call : {})
|
|
413
|
-
const
|
|
973
|
+
const hasChiefRiskAck = Boolean(execCtx.hasChiefRiskAck)
|
|
974
|
+
const permissionMode = normalizePermissionMode(execCtx.permissionMode, { requireAck: true, hasChiefRiskAck })
|
|
414
975
|
const cwd = String(execCtx.cwd || process.cwd())
|
|
415
976
|
const rootId = String(execCtx.rootId || '')
|
|
416
977
|
const board = execCtx.board || {}
|
|
417
978
|
const readOnlyToolsOnly = Boolean(execCtx.readOnlyToolsOnly)
|
|
979
|
+
const approvedOnce = Boolean(execCtx.approvedOnce)
|
|
980
|
+
|
|
981
|
+
const writeAudit = (entry) => {
|
|
982
|
+
if (typeof execCtx.recordAuditFn === 'function') {
|
|
983
|
+
try {
|
|
984
|
+
execCtx.recordAuditFn({
|
|
985
|
+
mode: permissionMode,
|
|
986
|
+
tool,
|
|
987
|
+
by: execCtx.by || 'chief',
|
|
988
|
+
...entry,
|
|
989
|
+
})
|
|
990
|
+
} catch {}
|
|
991
|
+
}
|
|
992
|
+
}
|
|
418
993
|
|
|
419
|
-
const deny = (error, badge) => ({
|
|
994
|
+
const deny = (error, badge, extra = {}) => ({
|
|
420
995
|
tool,
|
|
421
996
|
ok: false,
|
|
422
997
|
denied: true,
|
|
423
998
|
error,
|
|
424
999
|
badge: badge || `⛔ 拒绝 ${tool}`,
|
|
1000
|
+
...extra,
|
|
425
1001
|
})
|
|
426
1002
|
|
|
427
1003
|
if (!tool) return deny('缺少工具名 tool')
|
|
428
|
-
|
|
1004
|
+
|
|
1005
|
+
const opClass = getToolOpClass(tool)
|
|
1006
|
+
if (readOnlyToolsOnly && opClass !== 'read') {
|
|
1007
|
+
writeAudit({ stage: 'read_only_guard', decision: 'denied', operation: tool, target: '', reason: '后台复盘仅允许只读核验', outcome: 'blocked' })
|
|
429
1008
|
return deny(`后台复盘轮次仅允许只读核验工具(${tool} 已跳过)`)
|
|
430
1009
|
}
|
|
431
1010
|
|
|
1011
|
+
const rawTargetPath = (tool === 'read_file' || tool === 'write_file' || tool === 'edit_file' || tool === 'list_dir' || tool === 'search_files')
|
|
1012
|
+
? String(args.path || '').trim()
|
|
1013
|
+
: ''
|
|
1014
|
+
const resolvedAbsTarget = rawTargetPath ? path.resolve(cwd, rawTargetPath) : ''
|
|
1015
|
+
const rawCommand = tool === 'run_command' ? String(args.command || args.cmd || '').trim() : ''
|
|
1016
|
+
|
|
1017
|
+
// Stage 3: 安全卫兵硬性规则(优先于任何权限等级与逐项批准)
|
|
1018
|
+
const guardRes = evaluateSafetyGuardHardRules({
|
|
1019
|
+
tool,
|
|
1020
|
+
opClass,
|
|
1021
|
+
targetPath: resolvedAbsTarget,
|
|
1022
|
+
command: rawCommand,
|
|
1023
|
+
args,
|
|
1024
|
+
cwd,
|
|
1025
|
+
board,
|
|
1026
|
+
})
|
|
1027
|
+
if (guardRes.blocked) {
|
|
1028
|
+
writeAudit({
|
|
1029
|
+
stage: 'safety_guard',
|
|
1030
|
+
decision: 'blocked',
|
|
1031
|
+
operation: tool,
|
|
1032
|
+
target: displayRelTarget(cwd, resolvedAbsTarget) || clamp(rawCommand, 80) || tool,
|
|
1033
|
+
reason: guardRes.reason,
|
|
1034
|
+
outcome: 'blocked',
|
|
1035
|
+
})
|
|
1036
|
+
return deny(guardRes.reason, guardRes.badge, { blockedBySafetyGuard: true })
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// Stage 4: 四级权限判定
|
|
1040
|
+
const gateRes = evaluateChiefPermissionGate({
|
|
1041
|
+
permissionMode,
|
|
1042
|
+
hasChiefRiskAck,
|
|
1043
|
+
opClass,
|
|
1044
|
+
tool,
|
|
1045
|
+
approvedOnce,
|
|
1046
|
+
})
|
|
1047
|
+
if (gateRes.decision === 'deny_mode' || gateRes.decision === 'deny_unacknowledged_l3') {
|
|
1048
|
+
writeAudit({
|
|
1049
|
+
stage: 'permission_gate',
|
|
1050
|
+
decision: gateRes.decision,
|
|
1051
|
+
operation: tool,
|
|
1052
|
+
target: rawTargetPath || clamp(rawCommand, 60) || String(args.agent || args.op || tool),
|
|
1053
|
+
reason: gateRes.error,
|
|
1054
|
+
outcome: 'denied',
|
|
1055
|
+
})
|
|
1056
|
+
return deny(gateRes.error, gateRes.badge, {
|
|
1057
|
+
deniedByMode: true,
|
|
1058
|
+
requiredMode: gateRes.requiredMode,
|
|
1059
|
+
currentMode: gateRes.mode,
|
|
1060
|
+
})
|
|
1061
|
+
}
|
|
1062
|
+
if (gateRes.decision === 'require_approval') {
|
|
1063
|
+
const meta = describeControlledOperationMeta(tool, args, cwd)
|
|
1064
|
+
const approvalObj = typeof execCtx.queueApprovalFn === 'function'
|
|
1065
|
+
? await execCtx.queueApprovalFn({
|
|
1066
|
+
category: meta.category,
|
|
1067
|
+
operationLabel: meta.operationLabel,
|
|
1068
|
+
targetLabel: meta.targetLabel,
|
|
1069
|
+
reason: meta.reason,
|
|
1070
|
+
impact: meta.impact,
|
|
1071
|
+
preview: meta.preview,
|
|
1072
|
+
kind: 'tool',
|
|
1073
|
+
payload: { tool, args: { ...args }, cwd, rootId, sessionId: execCtx.sessionId || rootId },
|
|
1074
|
+
by: execCtx.by || 'chief',
|
|
1075
|
+
})
|
|
1076
|
+
: null
|
|
1077
|
+
writeAudit({
|
|
1078
|
+
stage: 'permission_gate',
|
|
1079
|
+
decision: 'pending_approval',
|
|
1080
|
+
operation: meta.operationLabel,
|
|
1081
|
+
target: meta.targetLabel,
|
|
1082
|
+
reason: meta.reason,
|
|
1083
|
+
outcome: 'pending',
|
|
1084
|
+
})
|
|
1085
|
+
return {
|
|
1086
|
+
tool,
|
|
1087
|
+
ok: false,
|
|
1088
|
+
pendingApproval: true,
|
|
1089
|
+
approvalId: (approvalObj && approvalObj.id) || '',
|
|
1090
|
+
approval: approvalObj || null,
|
|
1091
|
+
error: `当前处于「L2 · 参谋模式」,操作「${meta.operationLabel} → ${meta.targetLabel}」已提交操作授权弹窗,等待用户点击「允许本次操作」。`,
|
|
1092
|
+
badge: `🛡️ 待确认 ${clamp(meta.targetLabel, 18)}`,
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
// Stage 5: 执行器
|
|
1097
|
+
const finish = (res, opLabel, targetLabel) => {
|
|
1098
|
+
writeAudit({
|
|
1099
|
+
stage: 'executor',
|
|
1100
|
+
decision: approvedOnce ? 'executed_approved' : 'executed',
|
|
1101
|
+
operation: opLabel || tool,
|
|
1102
|
+
target: targetLabel || '',
|
|
1103
|
+
reason: clamp(args.reason || res.error || '', 140),
|
|
1104
|
+
outcome: res.ok ? 'ok' : 'error',
|
|
1105
|
+
})
|
|
1106
|
+
return res
|
|
1107
|
+
}
|
|
1108
|
+
|
|
432
1109
|
switch (tool) {
|
|
433
1110
|
case 'read_file': {
|
|
434
1111
|
const targetRel = String(args.path || '').trim()
|
|
435
|
-
if (!targetRel) return deny('read_file 需要 path 参数')
|
|
1112
|
+
if (!targetRel) return finish(deny('read_file 需要 path 参数'), '读取文件', '')
|
|
436
1113
|
const abs = path.resolve(cwd, targetRel)
|
|
437
|
-
if (
|
|
438
|
-
return deny(`安全护栏拒绝读取凭据文件:${path.basename(abs)}`, `🛡️ 拦截读取凭据`)
|
|
439
|
-
}
|
|
440
|
-
if (!fs.existsSync(abs)) return { tool, ok: false, error: `文件不存在:${abs}`, badge: `⚠️ 未找到 ${path.basename(abs)}` }
|
|
1114
|
+
if (!fs.existsSync(abs)) return finish({ tool, ok: false, error: `文件不存在:${abs}`, badge: `⚠️ 未找到 ${path.basename(abs)}` }, '读取文件', displayRelTarget(cwd, abs))
|
|
441
1115
|
try {
|
|
442
1116
|
const raw = fs.readFileSync(abs, 'utf8')
|
|
443
1117
|
const lines = raw.split(/\r?\n/)
|
|
444
1118
|
const startLine = Math.max(1, Math.round(Number(args.startLine) || 1))
|
|
445
1119
|
const endLine = Math.min(lines.length, Math.max(startLine, Math.round(Number(args.endLine) || (startLine + 179))))
|
|
446
1120
|
const numbered = lines.slice(startLine - 1, endLine).map((l, idx) => `${startLine + idx}: ${l}`).join('\n')
|
|
447
|
-
return {
|
|
1121
|
+
return finish({
|
|
448
1122
|
tool,
|
|
449
1123
|
ok: true,
|
|
450
1124
|
path: abs,
|
|
@@ -452,16 +1126,16 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
|
|
|
452
1126
|
range: `${startLine}-${endLine}`,
|
|
453
1127
|
content: truncateMiddle(numbered, 14_000),
|
|
454
1128
|
badge: `📖 读取 ${path.basename(abs)}`,
|
|
455
|
-
}
|
|
1129
|
+
}, '读取文件', displayRelTarget(cwd, abs))
|
|
456
1130
|
} catch (err) {
|
|
457
|
-
return { tool, ok: false, error: String(err && err.message ? err.message : err), badge:
|
|
1131
|
+
return finish({ tool, ok: false, error: String(err && err.message ? err.message : err), badge: '⚠️ 读取失败' }, '读取文件', displayRelTarget(cwd, abs))
|
|
458
1132
|
}
|
|
459
1133
|
}
|
|
460
1134
|
|
|
461
1135
|
case 'list_dir': {
|
|
462
1136
|
const targetRel = String(args.path || '.').trim() || '.'
|
|
463
1137
|
const abs = path.resolve(cwd, targetRel)
|
|
464
|
-
if (!fs.existsSync(abs)) return { tool, ok: false, error: `目录不存在:${abs}`, badge:
|
|
1138
|
+
if (!fs.existsSync(abs)) return finish({ tool, ok: false, error: `目录不存在:${abs}`, badge: '⚠️ 目录不存在' }, '列目录', displayRelTarget(cwd, abs))
|
|
465
1139
|
try {
|
|
466
1140
|
const items = fs.readdirSync(abs, { withFileTypes: true }).slice(0, 120).map(ent => {
|
|
467
1141
|
let size = 0
|
|
@@ -470,49 +1144,65 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
|
|
|
470
1144
|
}
|
|
471
1145
|
return { name: ent.name, type: ent.isDirectory() ? 'dir' : 'file', ...(ent.isFile() ? { size } : {}) }
|
|
472
1146
|
})
|
|
473
|
-
return { tool, ok: true, path: abs, items, badge: `📂 列目录 ${path.basename(abs) || abs}` }
|
|
1147
|
+
return finish({ tool, ok: true, path: abs, items, badge: `📂 列目录 ${path.basename(abs) || abs}` }, '列目录', displayRelTarget(cwd, abs))
|
|
474
1148
|
} catch (err) {
|
|
475
|
-
return { tool, ok: false, error: String(err && err.message ? err.message : err), badge:
|
|
1149
|
+
return finish({ tool, ok: false, error: String(err && err.message ? err.message : err), badge: '⚠️ 列目录失败' }, '列目录', displayRelTarget(cwd, abs))
|
|
476
1150
|
}
|
|
477
1151
|
}
|
|
478
1152
|
|
|
479
1153
|
case 'search_files': {
|
|
480
1154
|
const pattern = String(args.pattern || args.query || '').trim()
|
|
481
|
-
if (!pattern) return deny('search_files 需要 pattern 参数')
|
|
1155
|
+
if (!pattern) return finish(deny('search_files 需要 pattern 参数'), '搜索代码', '')
|
|
482
1156
|
const searchRoot = path.resolve(cwd, String(args.path || '.').trim() || '.')
|
|
483
|
-
if (!fs.existsSync(searchRoot)) return { tool, ok: false, error: `搜索目录不存在:${searchRoot}`, badge:
|
|
1157
|
+
if (!fs.existsSync(searchRoot)) return finish({ tool, ok: false, error: `搜索目录不存在:${searchRoot}`, badge: '⚠️ 搜索目录不存在' }, '搜索代码', displayRelTarget(cwd, searchRoot))
|
|
484
1158
|
const maxHits = Math.min(50, Math.max(1, Math.round(Number(args.maxHits) || 30)))
|
|
485
1159
|
let hits = await runRgSearch(searchRoot, pattern, maxHits)
|
|
486
1160
|
if (hits === null) hits = searchFilesFallbackNode(searchRoot, pattern, maxHits)
|
|
487
|
-
return { tool, ok: true, path: searchRoot, pattern, hits, count: hits.length, badge: `🔎 搜索 "${clamp(pattern, 18)}"` }
|
|
1161
|
+
return finish({ tool, ok: true, path: searchRoot, pattern, hits, count: hits.length, badge: `🔎 搜索 "${clamp(pattern, 18)}"` }, '搜索代码', clamp(pattern, 40))
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
case 'request_permission_elevation': {
|
|
1165
|
+
const rawTarget = String(args.targetMode || args.target_mode || args.target || 'strategist').trim()
|
|
1166
|
+
const targetMode = normalizePermissionMode(rawTarget)
|
|
1167
|
+
if (permissionRank(targetMode) <= permissionRank(permissionMode)) {
|
|
1168
|
+
return finish({
|
|
1169
|
+
tool,
|
|
1170
|
+
ok: false,
|
|
1171
|
+
error: `目标权限 ${CHIEF_PERMISSION_META[targetMode].level} 不高于当前权限 ${CHIEF_PERMISSION_META[permissionMode].level}`,
|
|
1172
|
+
badge: '⚠️ 无需提权',
|
|
1173
|
+
}, '申请提权', targetMode)
|
|
1174
|
+
}
|
|
1175
|
+
const reason = clamp(args.reason || args.rationale || '执行当前工作任务需要更高权限', 220)
|
|
1176
|
+
const summaryText = clamp(args.requestedActionSummary || args.action_summary || args.actionSummary || args.summary || '', 180)
|
|
1177
|
+
const reqObj = typeof execCtx.requestElevationFn === 'function'
|
|
1178
|
+
? await execCtx.requestElevationFn({
|
|
1179
|
+
fromMode: permissionMode,
|
|
1180
|
+
targetMode,
|
|
1181
|
+
reason,
|
|
1182
|
+
requestedActionSummary: summaryText,
|
|
1183
|
+
by: execCtx.by || 'chief',
|
|
1184
|
+
})
|
|
1185
|
+
: null
|
|
1186
|
+
return finish({
|
|
1187
|
+
tool,
|
|
1188
|
+
ok: true,
|
|
1189
|
+
elevationRequested: true,
|
|
1190
|
+
elevation: reqObj || { fromMode: permissionMode, targetMode, reason, requestedActionSummary: summaryText },
|
|
1191
|
+
badge: `🔐 已请示提权至 ${CHIEF_PERMISSION_META[targetMode].level}`,
|
|
1192
|
+
}, '申请提权', `${CHIEF_PERMISSION_META[permissionMode].level} -> ${CHIEF_PERMISSION_META[targetMode].level}`)
|
|
488
1193
|
}
|
|
489
1194
|
|
|
490
1195
|
case 'write_file': {
|
|
491
1196
|
const targetRel = String(args.path || '').trim()
|
|
492
|
-
if (!targetRel) return deny('write_file 需要 path 参数')
|
|
1197
|
+
if (!targetRel) return finish(deny('write_file 需要 path 参数'), '写入文件', '')
|
|
493
1198
|
const abs = path.resolve(cwd, targetRel)
|
|
494
|
-
|
|
495
|
-
return deny('当前参谋长权限为「👁 仅可查看」,已拦截文件写入。请切至「工作区内修改」或「🛡️ 完全权限」。', '🔒 仅可查看拦写')
|
|
496
|
-
}
|
|
497
|
-
if (permissionMode === 'auto-review') {
|
|
498
|
-
return deny('当前参谋长权限为「🔍 自动审查 EXP」,写入需转为人工确认或切回「🛡️ 完全权限」。', '🔍 待审查拦写')
|
|
499
|
-
}
|
|
500
|
-
if (permissionMode === 'workspace-write' && !isPathInsideWorkspace(cwd, abs)) {
|
|
501
|
-
return deny(`当前权限为「工作区内修改」,拒绝写入工作区外的路径:${abs}`, '🔒 越界拦写')
|
|
502
|
-
}
|
|
503
|
-
if (isSensitiveCredentialPath(abs)) {
|
|
504
|
-
return deny(`安全护栏拒绝写入凭据文件:${path.basename(abs)}`, '🛡️ 拦截写凭据')
|
|
505
|
-
}
|
|
506
|
-
const boundCheck = checkForbiddenBounds(board, 'write_file', abs)
|
|
507
|
-
if (boundCheck.blocked) {
|
|
508
|
-
return deny(`命中禁止红线【${boundCheck.matchedRule}】,已拦截写入 ${abs}`, '🛡 红线拦写')
|
|
509
|
-
}
|
|
1199
|
+
const contentStr = normalizeTextContent(args.content)
|
|
510
1200
|
try {
|
|
511
1201
|
fs.mkdirSync(path.dirname(abs), { recursive: true })
|
|
512
|
-
fs.writeFileSync(abs,
|
|
513
|
-
return { tool, ok: true, path: abs, bytes: Buffer.byteLength(
|
|
1202
|
+
fs.writeFileSync(abs, contentStr, 'utf8')
|
|
1203
|
+
return finish({ tool, ok: true, path: abs, bytes: Buffer.byteLength(contentStr, 'utf8'), badge: `✍️ 写入 ${path.basename(abs)}` }, '写入工作区文件', displayRelTarget(cwd, abs))
|
|
514
1204
|
} catch (err) {
|
|
515
|
-
return { tool, ok: false, error: String(err && err.message ? err.message : err), badge:
|
|
1205
|
+
return finish({ tool, ok: false, error: String(err && err.message ? err.message : err), badge: '⚠️ 写入失败' }, '写入工作区文件', displayRelTarget(cwd, abs))
|
|
516
1206
|
}
|
|
517
1207
|
}
|
|
518
1208
|
|
|
@@ -520,57 +1210,28 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
|
|
|
520
1210
|
const targetRel = String(args.path || '').trim()
|
|
521
1211
|
const targetStr = String(args.target ?? '')
|
|
522
1212
|
const replaceStr = String(args.replacement ?? '')
|
|
523
|
-
if (!targetRel || !targetStr) return deny('edit_file 需要 path 与 target 参数')
|
|
1213
|
+
if (!targetRel || !targetStr) return finish(deny('edit_file 需要 path 与 target 参数'), '修改工作区文件', '')
|
|
524
1214
|
const abs = path.resolve(cwd, targetRel)
|
|
525
|
-
if (
|
|
526
|
-
return deny('当前参谋长权限为「👁 仅可查看」,已拦截文件编辑。', '🔒 仅可查看拦改')
|
|
527
|
-
}
|
|
528
|
-
if (permissionMode === 'auto-review') {
|
|
529
|
-
return deny('当前参谋长权限为「🔍 自动审查 EXP」,修改文件请切回「🛡️ 完全权限」。', '🔍 待审查拦改')
|
|
530
|
-
}
|
|
531
|
-
if (permissionMode === 'workspace-write' && !isPathInsideWorkspace(cwd, abs)) {
|
|
532
|
-
return deny(`当前权限为「工作区内修改」,拒绝编辑工作区外的路径:${abs}`, '🔒 越界拦改')
|
|
533
|
-
}
|
|
534
|
-
if (isSensitiveCredentialPath(abs)) {
|
|
535
|
-
return deny(`安全护栏拒绝编辑凭据文件:${path.basename(abs)}`, '🛡️ 拦截改凭据')
|
|
536
|
-
}
|
|
537
|
-
const boundCheck = checkForbiddenBounds(board, 'edit_file', abs)
|
|
538
|
-
if (boundCheck.blocked) {
|
|
539
|
-
return deny(`命中禁止红线【${boundCheck.matchedRule}】,已拦截编辑 ${abs}`, '🛡 红线拦改')
|
|
540
|
-
}
|
|
541
|
-
if (!fs.existsSync(abs)) return { tool, ok: false, error: `目标文件不存在:${abs}`, badge: `⚠️ 未找到 ${path.basename(abs)}` }
|
|
1215
|
+
if (!fs.existsSync(abs)) return finish({ tool, ok: false, error: `目标文件不存在:${abs}`, badge: `⚠️ 未找到 ${path.basename(abs)}` }, '修改工作区文件', displayRelTarget(cwd, abs))
|
|
542
1216
|
try {
|
|
543
1217
|
const prev = fs.readFileSync(abs, 'utf8')
|
|
544
1218
|
const idx = prev.indexOf(targetStr)
|
|
545
|
-
if (idx < 0) return { tool, ok: false, error: `未在 ${path.basename(abs)} 中匹配到 target 文本`, badge:
|
|
1219
|
+
if (idx < 0) return finish({ tool, ok: false, error: `未在 ${path.basename(abs)} 中匹配到 target 文本`, badge: '⚠️ 替换未命中' }, '修改工作区文件', displayRelTarget(cwd, abs))
|
|
546
1220
|
const next = prev.slice(0, idx) + replaceStr + prev.slice(idx + targetStr.length)
|
|
547
1221
|
fs.writeFileSync(abs, next, 'utf8')
|
|
548
|
-
return { tool, ok: true, path: abs, badge: `✏️ 修改 ${path.basename(abs)}` }
|
|
1222
|
+
return finish({ tool, ok: true, path: abs, badge: `✏️ 修改 ${path.basename(abs)}` }, '修改工作区文件', displayRelTarget(cwd, abs))
|
|
549
1223
|
} catch (err) {
|
|
550
|
-
return { tool, ok: false, error: String(err && err.message ? err.message : err), badge:
|
|
1224
|
+
return finish({ tool, ok: false, error: String(err && err.message ? err.message : err), badge: '⚠️ 编辑失败' }, '修改工作区文件', displayRelTarget(cwd, abs))
|
|
551
1225
|
}
|
|
552
1226
|
}
|
|
553
1227
|
|
|
554
1228
|
case 'run_command': {
|
|
555
1229
|
const command = String(args.command || args.cmd || '').trim()
|
|
556
|
-
if (!command) return deny('run_command 需要 command 参数')
|
|
1230
|
+
if (!command) return finish(deny('run_command 需要 command 参数'), '执行系统命令', '')
|
|
557
1231
|
const runCwd = path.resolve(cwd, String(args.cwd || '.').trim() || '.')
|
|
558
|
-
|
|
559
|
-
if (boundCheck.blocked) {
|
|
560
|
-
return deny(`命中禁止红线【${boundCheck.matchedRule}】,参谋长拒绝执行命令:${clamp(command, 80)}`, '🛡 红线拦截命令')
|
|
561
|
-
}
|
|
562
|
-
if (permissionMode === 'read-only' && !isReadOnlyShellCommand(command)) {
|
|
563
|
-
return deny(`当前权限为「👁 仅可查看」,仅允许只读检查命令,已拦截:${clamp(command, 60)}`, '🔒 仅查看拦截命令')
|
|
564
|
-
}
|
|
565
|
-
if (permissionMode === 'auto-review' && !isReadOnlyShellCommand(command)) {
|
|
566
|
-
return deny(`当前权限为「🔍 自动审查 EXP」,变更性命令需人工授权或切至「🛡️ 完全权限」:${clamp(command, 60)}`, '🔍 待审查拦截')
|
|
567
|
-
}
|
|
568
|
-
if (permissionMode === 'workspace-write' && !isPathInsideWorkspace(cwd, runCwd)) {
|
|
569
|
-
return deny(`当前权限为「工作区内修改」,拒绝在工作区外目录执行命令:${runCwd}`, '🔒 工作区外拒跑')
|
|
570
|
-
}
|
|
571
|
-
if (!fs.existsSync(runCwd)) return { tool, ok: false, error: `工作目录不存在:${runCwd}`, badge: `⚠️ 目录不存在` }
|
|
1232
|
+
if (!fs.existsSync(runCwd)) return finish({ tool, ok: false, error: `工作目录不存在:${runCwd}`, badge: '⚠️ 目录不存在' }, '执行系统命令', clamp(command, 60))
|
|
572
1233
|
const execOut = await runSubprocess(command, runCwd, args.timeoutMs)
|
|
573
|
-
return {
|
|
1234
|
+
return finish({
|
|
574
1235
|
tool,
|
|
575
1236
|
ok: execOut.ok,
|
|
576
1237
|
exitCode: execOut.exitCode,
|
|
@@ -579,15 +1240,33 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
|
|
|
579
1240
|
stdout: execOut.stdout,
|
|
580
1241
|
stderr: execOut.stderr,
|
|
581
1242
|
badge: `⚡ 执行 (${execOut.timedOut ? '超时' : 'exit ' + execOut.exitCode})`,
|
|
1243
|
+
}, '执行系统命令', clamp(command, 60))
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
case 'main_agent_control': {
|
|
1247
|
+
if (typeof deps.controlMainAgent !== 'function') {
|
|
1248
|
+
return finish({ tool, ok: false, error: '当前宿主未挂载主代理控制接口', badge: '⚠️ 无主代理控制' }, '调整主代理', String(args.op || 'control'))
|
|
582
1249
|
}
|
|
1250
|
+
const ctrlRes = await deps.controlMainAgent({
|
|
1251
|
+
rootId,
|
|
1252
|
+
sessionId: execCtx.sessionId || rootId,
|
|
1253
|
+
op: String(args.op || 'steer').trim(),
|
|
1254
|
+
modelRef: String(args.modelRef || args.model || '').trim(),
|
|
1255
|
+
reasoningEffort: String(args.reasoningEffort || '').trim(),
|
|
1256
|
+
message: String(args.message || args.prompt || args.text || '').trim(),
|
|
1257
|
+
reason: String(args.reason || '').trim(),
|
|
1258
|
+
})
|
|
1259
|
+
return finish({
|
|
1260
|
+
tool,
|
|
1261
|
+
ok: Boolean(ctrlRes && ctrlRes.ok),
|
|
1262
|
+
...(ctrlRes || {}),
|
|
1263
|
+
badge: ctrlRes && ctrlRes.ok ? (ctrlRes.badge || '🎛 已调整主代理') : '⚠️ 主代理控制失败',
|
|
1264
|
+
}, '调整主代理', String(args.modelRef || args.op || 'lead'))
|
|
583
1265
|
}
|
|
584
1266
|
|
|
585
1267
|
case 'subagent_dispatch': {
|
|
586
|
-
if (permissionMode === 'read-only') {
|
|
587
|
-
return deny('当前权限为「👁 仅可查看」,无法派发子代理任务。', '🔒 只读禁派')
|
|
588
|
-
}
|
|
589
1268
|
const prompt = String(args.prompt || args.message || args.text || '').trim()
|
|
590
|
-
if (!prompt) return deny('subagent_dispatch 需要 prompt 指令')
|
|
1269
|
+
if (!prompt) return finish(deny('subagent_dispatch 需要 prompt 指令'), '派发子代理', '')
|
|
591
1270
|
let taskId = String(args.taskId || args.id || '').trim()
|
|
592
1271
|
if (!taskId && typeof deps.runAction === 'function') {
|
|
593
1272
|
const addRes = deps.runAction({
|
|
@@ -602,7 +1281,7 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
|
|
|
602
1281
|
}
|
|
603
1282
|
}
|
|
604
1283
|
if (typeof deps.executeSubagentAction !== 'function') {
|
|
605
|
-
return { tool, ok: false, error: '当前宿主未挂载子代理调度接口', badge: '⚠️ 无子代理引擎' }
|
|
1284
|
+
return finish({ tool, ok: false, error: '当前宿主未挂载子代理调度接口', badge: '⚠️ 无子代理引擎' }, '派发子代理', String(args.agent || ''))
|
|
606
1285
|
}
|
|
607
1286
|
const dRes = await deps.executeSubagentAction({
|
|
608
1287
|
action: 'task.dispatch',
|
|
@@ -614,17 +1293,18 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
|
|
|
614
1293
|
session: rootId,
|
|
615
1294
|
by: 'chief',
|
|
616
1295
|
})
|
|
617
|
-
return {
|
|
1296
|
+
return finish({
|
|
618
1297
|
tool,
|
|
619
1298
|
ok: Boolean(dRes && dRes.ok),
|
|
620
1299
|
...(dRes || {}),
|
|
621
1300
|
badge: dRes && dRes.ok ? `🚀 派发 @${dRes.dispatched?.agent || args.agent || 'worker'}` : '⚠️ 派发失败',
|
|
622
|
-
}
|
|
1301
|
+
}, '派发子代理', '@' + String((dRes && dRes.dispatched && dRes.dispatched.agent) || args.agent || 'worker'))
|
|
623
1302
|
}
|
|
624
1303
|
|
|
625
1304
|
case 'subagent_steer': {
|
|
626
|
-
if (
|
|
627
|
-
|
|
1305
|
+
if (typeof deps.executeSubagentAction !== 'function') {
|
|
1306
|
+
return finish({ tool, ok: false, error: '当前宿主未挂载子代理接口' }, '引导子代理', String(args.agent || ''))
|
|
1307
|
+
}
|
|
628
1308
|
const sRes = await deps.executeSubagentAction({
|
|
629
1309
|
action: 'team.steer',
|
|
630
1310
|
agent: args.agent || args.target || '',
|
|
@@ -633,12 +1313,18 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
|
|
|
633
1313
|
session: rootId,
|
|
634
1314
|
by: 'chief',
|
|
635
1315
|
})
|
|
636
|
-
return
|
|
1316
|
+
return finish({
|
|
1317
|
+
tool,
|
|
1318
|
+
ok: Boolean(sRes && sRes.ok),
|
|
1319
|
+
...(sRes || {}),
|
|
1320
|
+
badge: sRes && sRes.ok ? `💬 引导 @${args.agent || 'worker'}` : '⚠️ 引导失败',
|
|
1321
|
+
}, '引导子代理', '@' + String(args.agent || args.target || 'worker'))
|
|
637
1322
|
}
|
|
638
1323
|
|
|
639
1324
|
case 'subagent_interrupt': {
|
|
640
|
-
if (
|
|
641
|
-
|
|
1325
|
+
if (typeof deps.executeSubagentAction !== 'function') {
|
|
1326
|
+
return finish({ tool, ok: false, error: '当前宿主未挂载子代理接口' }, '中断子代理', String(args.agent || ''))
|
|
1327
|
+
}
|
|
642
1328
|
const iRes = await deps.executeSubagentAction({
|
|
643
1329
|
action: 'team.interrupt',
|
|
644
1330
|
agent: args.agent || args.target || '',
|
|
@@ -646,13 +1332,17 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
|
|
|
646
1332
|
session: rootId,
|
|
647
1333
|
by: 'chief',
|
|
648
1334
|
})
|
|
649
|
-
return
|
|
1335
|
+
return finish({
|
|
1336
|
+
tool,
|
|
1337
|
+
ok: Boolean(iRes && iRes.ok),
|
|
1338
|
+
...(iRes || {}),
|
|
1339
|
+
badge: iRes && iRes.ok ? `⏹ 中断 @${args.agent || 'worker'}` : '⚠️ 中断失败',
|
|
1340
|
+
}, '中断子代理', '@' + String(args.agent || args.target || 'worker'))
|
|
650
1341
|
}
|
|
651
1342
|
|
|
652
1343
|
case 'archive_write': {
|
|
653
|
-
if (permissionMode === 'read-only') return deny('当前权限为「👁 仅可查看」,不能写入档案柜。')
|
|
654
1344
|
if (typeof execCtx.upsertArchiveFn !== 'function') {
|
|
655
|
-
return { tool, ok: false, error: '档案写入服务未就绪', badge: '⚠️ 无档案写口' }
|
|
1345
|
+
return finish({ tool, ok: false, error: '档案写入服务未就绪', badge: '⚠️ 无档案写口' }, '写参谋档案', String(args.title || ''))
|
|
656
1346
|
}
|
|
657
1347
|
const scope = args.vaultScope === 'global' ? 'global' : 'session'
|
|
658
1348
|
const out = await execCtx.upsertArchiveFn({
|
|
@@ -663,48 +1353,47 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
|
|
|
663
1353
|
body: String(args.body || args.text || ''),
|
|
664
1354
|
tags: Array.isArray(args.tags) ? args.tags : [],
|
|
665
1355
|
})
|
|
666
|
-
return {
|
|
1356
|
+
return finish({
|
|
667
1357
|
tool,
|
|
668
1358
|
ok: Boolean(out && out.ok),
|
|
669
1359
|
...(out || {}),
|
|
670
1360
|
badge: out && out.ok ? `🗄️ 归档(${scope === 'global' ? '全局' : '本会话'})` : '⚠️ 归档失败',
|
|
671
|
-
}
|
|
1361
|
+
}, '写参谋档案', clamp(args.title || scope, 40))
|
|
672
1362
|
}
|
|
673
1363
|
|
|
674
1364
|
case 'session_compact': {
|
|
675
|
-
if (permissionMode === 'read-only') return deny('当前权限为「👁 仅可查看」,不能触发上下文压缩。')
|
|
676
1365
|
if (typeof execCtx.compactNowFn !== 'function') {
|
|
677
|
-
return { tool, ok: false, error: '压缩服务未就绪', badge: '⚠️ 无压缩引擎' }
|
|
1366
|
+
return finish({ tool, ok: false, error: '压缩服务未就绪', badge: '⚠️ 无压缩引擎' }, '压缩主对话', 'current')
|
|
678
1367
|
}
|
|
679
1368
|
try {
|
|
680
1369
|
const cRes = await execCtx.compactNowFn(String(args.reason || '参谋长主动执行抢救与上下文压缩'))
|
|
681
1370
|
if (cRes && cRes.ok) {
|
|
682
|
-
return {
|
|
1371
|
+
return finish({
|
|
683
1372
|
tool,
|
|
684
1373
|
ok: true,
|
|
685
1374
|
...cRes,
|
|
686
1375
|
badge: cRes.noop ? '🗄️ 已归档(免压)' : '🗜 完成抢救压缩',
|
|
687
|
-
}
|
|
1376
|
+
}, '压缩主对话', 'current')
|
|
688
1377
|
}
|
|
689
|
-
return {
|
|
1378
|
+
return finish({
|
|
690
1379
|
tool,
|
|
691
1380
|
ok: false,
|
|
692
1381
|
...(cRes && typeof cRes === 'object' ? cRes : { error: String(cRes || '压缩未完成') }),
|
|
693
1382
|
error: (cRes && cRes.error) || '压缩未完成',
|
|
694
1383
|
badge: '⚠️ 压缩未完成',
|
|
695
|
-
}
|
|
1384
|
+
}, '压缩主对话', 'current')
|
|
696
1385
|
} catch (e) {
|
|
697
|
-
return {
|
|
1386
|
+
return finish({
|
|
698
1387
|
tool,
|
|
699
1388
|
ok: false,
|
|
700
1389
|
error: (e && e.message) || String(e || '压缩执行异常'),
|
|
701
1390
|
badge: '⚠️ 压缩异常',
|
|
702
|
-
}
|
|
1391
|
+
}, '压缩主对话', 'current')
|
|
703
1392
|
}
|
|
704
1393
|
}
|
|
705
1394
|
|
|
706
1395
|
default:
|
|
707
|
-
return deny(
|
|
1396
|
+
return finish(deny(`未知参谋工具:${tool}`, `⚠️ 未知工具 ${tool}`), tool, '')
|
|
708
1397
|
}
|
|
709
1398
|
}
|
|
710
1399
|
|
|
@@ -719,6 +1408,7 @@ export async function runChiefAgenticLoop(deps, {
|
|
|
719
1408
|
imageBlocks = [],
|
|
720
1409
|
allowTextFallbackOnVisionMiss = false,
|
|
721
1410
|
permissionMode = DEFAULT_CHIEF_PERMISSION_MODE,
|
|
1411
|
+
hasChiefRiskAck = false,
|
|
722
1412
|
board = null,
|
|
723
1413
|
maxSteps = 4,
|
|
724
1414
|
readOnlyToolsOnly = false,
|
|
@@ -727,11 +1417,16 @@ export async function runChiefAgenticLoop(deps, {
|
|
|
727
1417
|
extractJsonFn,
|
|
728
1418
|
upsertArchiveFn,
|
|
729
1419
|
compactNowFn,
|
|
1420
|
+
queueApprovalFn,
|
|
1421
|
+
requestElevationFn,
|
|
1422
|
+
recordAuditFn,
|
|
730
1423
|
} = {}) {
|
|
731
|
-
const perm = normalizePermissionMode(permissionMode)
|
|
1424
|
+
const perm = normalizePermissionMode(permissionMode, { requireAck: true, hasChiefRiskAck })
|
|
732
1425
|
const cwd = (typeof deps?.getSessionCwd === 'function' ? deps.getSessionCwd(rootId || sessionId) : '') || process.cwd()
|
|
733
1426
|
const toolBadges = []
|
|
734
1427
|
const toolRecords = []
|
|
1428
|
+
const pendingApprovals = []
|
|
1429
|
+
const elevationRequests = []
|
|
735
1430
|
let prompt = String(initialPrompt || '')
|
|
736
1431
|
let lastLlmRes = null
|
|
737
1432
|
let parsed = null
|
|
@@ -751,17 +1446,18 @@ export async function runChiefAgenticLoop(deps, {
|
|
|
751
1446
|
allowTextFallbackOnVisionMiss,
|
|
752
1447
|
})
|
|
753
1448
|
if (!lastLlmRes || !lastLlmRes.ok) {
|
|
754
|
-
return { ok: false, llmRes: lastLlmRes, parsed: null, toolBadges, toolRecords }
|
|
1449
|
+
return { ok: false, llmRes: lastLlmRes, parsed: null, toolBadges, toolRecords, pendingApprovals, elevationRequests }
|
|
755
1450
|
}
|
|
756
1451
|
const cleanedRes = cleanRes(lastLlmRes)
|
|
757
1452
|
parsed = typeof extractJsonFn === 'function' ? extractJsonFn(cleanedRes.text) : null
|
|
758
1453
|
if (parsed && typeof parsed.reply === 'string') {
|
|
759
1454
|
parsed.reply = stripToolCallMarkup(parsed.reply)
|
|
760
1455
|
}
|
|
761
|
-
return { ok: true, llmRes: cleanedRes, parsed, toolBadges, toolRecords }
|
|
1456
|
+
return { ok: true, llmRes: cleanedRes, parsed, toolBadges, toolRecords, pendingApprovals, elevationRequests }
|
|
762
1457
|
}
|
|
763
1458
|
|
|
764
|
-
const
|
|
1459
|
+
const meta = CHIEF_PERMISSION_META[perm] || CHIEF_PERMISSION_META.advisor
|
|
1460
|
+
const permHeader = `\n\n[当前参谋系统权限级别] permissionMode="${perm}" (${meta.level} · ${meta.title}) — ${meta.tagline}${perm === 'strategist' ? ' 所有工作区/系统命令/工作流变更工具均会进入「逐项操作授权弹窗」,需用户点击允许后方可执行。' : ''}`
|
|
765
1461
|
const stepsLimit = Math.max(1, maxSteps)
|
|
766
1462
|
let ranToolsOnLastStep = false
|
|
767
1463
|
|
|
@@ -774,7 +1470,7 @@ export async function runChiefAgenticLoop(deps, {
|
|
|
774
1470
|
allowTextFallbackOnVisionMiss,
|
|
775
1471
|
})
|
|
776
1472
|
if (!lastLlmRes || !lastLlmRes.ok) {
|
|
777
|
-
return { ok: false, llmRes: lastLlmRes, parsed: null, toolBadges, toolRecords }
|
|
1473
|
+
return { ok: false, llmRes: lastLlmRes, parsed: null, toolBadges, toolRecords, pendingApprovals, elevationRequests }
|
|
778
1474
|
}
|
|
779
1475
|
parsed = typeof extractJsonFn === 'function' ? extractJsonFn(lastLlmRes.text) : null
|
|
780
1476
|
const jsonCalls = parsed && Array.isArray(parsed.toolCalls) ? parsed.toolCalls.filter(c => c && (c.tool || c.name)).slice(0, 4) : []
|
|
@@ -788,10 +1484,9 @@ export async function runChiefAgenticLoop(deps, {
|
|
|
788
1484
|
if (parsed && typeof parsed.reply === 'string') {
|
|
789
1485
|
parsed.reply = stripToolCallMarkup(parsed.reply)
|
|
790
1486
|
}
|
|
791
|
-
return { ok: true, llmRes: cleanedRes, parsed, toolBadges, toolRecords }
|
|
1487
|
+
return { ok: true, llmRes: cleanedRes, parsed, toolBadges, toolRecords, pendingApprovals, elevationRequests }
|
|
792
1488
|
}
|
|
793
1489
|
|
|
794
|
-
// 执行本轮工具调用
|
|
795
1490
|
ranToolsOnLastStep = true
|
|
796
1491
|
const stepOutputs = []
|
|
797
1492
|
for (const c of calls) {
|
|
@@ -800,11 +1495,17 @@ export async function runChiefAgenticLoop(deps, {
|
|
|
800
1495
|
sessionId: sessionId || rootId,
|
|
801
1496
|
cwd,
|
|
802
1497
|
permissionMode: perm,
|
|
1498
|
+
hasChiefRiskAck,
|
|
803
1499
|
board,
|
|
804
1500
|
readOnlyToolsOnly,
|
|
805
1501
|
upsertArchiveFn,
|
|
806
1502
|
compactNowFn,
|
|
1503
|
+
queueApprovalFn,
|
|
1504
|
+
requestElevationFn,
|
|
1505
|
+
recordAuditFn,
|
|
807
1506
|
})
|
|
1507
|
+
if (execRes.pendingApproval && execRes.approval) pendingApprovals.push(execRes.approval)
|
|
1508
|
+
if (execRes.elevationRequested && execRes.elevation) elevationRequests.push(execRes.elevation)
|
|
808
1509
|
toolRecords.push({ step: step + 1, call: c, result: execRes })
|
|
809
1510
|
if (execRes.badge && !toolBadges.includes(execRes.badge)) {
|
|
810
1511
|
toolBadges.push(execRes.badge)
|
|
@@ -816,6 +1517,9 @@ export async function runChiefAgenticLoop(deps, {
|
|
|
816
1517
|
})
|
|
817
1518
|
}
|
|
818
1519
|
|
|
1520
|
+
const allWaitingUser = stepOutputs.every(s =>
|
|
1521
|
+
s.result && (s.result.pendingApproval || s.result.elevationRequested || s.result.deniedByMode),
|
|
1522
|
+
)
|
|
819
1523
|
const obsBlock = stepOutputs.map((item, i) => [
|
|
820
1524
|
`### 工具 #${i + 1} \`${item.tool}\` 执行回执`,
|
|
821
1525
|
JSON.stringify(item.result, null, 2),
|
|
@@ -828,9 +1532,11 @@ export async function runChiefAgenticLoop(deps, {
|
|
|
828
1532
|
`## 第 ${step + 1} 步实权工具真实执行结果`,
|
|
829
1533
|
obsBlock,
|
|
830
1534
|
'',
|
|
831
|
-
|
|
832
|
-
? '
|
|
833
|
-
:
|
|
1535
|
+
allWaitingUser
|
|
1536
|
+
? '以上受控操作已拦截并进入等待用户弹窗确认或申请提权流程。**严禁再重复调用同一被拒/待批工具**;若尚未调用 `request_permission_elevation` 且需要更高权限,可在最终 JSON 中附带 `"elevationRequest"` 或只读汇总当前分析结果后去掉 `"toolCalls"` 结束本轮。'
|
|
1537
|
+
: (isFinalStepSoon
|
|
1538
|
+
? '你已接近本轮工具调用步数上限,请立即基于上述真实回执输出最终结论 JSON(务必不要再带 `"toolCalls"` 或任何 DSML/XML 标签)。'
|
|
1539
|
+
: '请根据上述真实回执决定:若仍需进一步查看/修改/验证则继续附带下一批 `"toolCalls"`;否则直接输出最终结论 JSON(不再包含 `"toolCalls"` 或 DSML 标签)。'),
|
|
834
1540
|
].join('\n')
|
|
835
1541
|
}
|
|
836
1542
|
|
|
@@ -857,5 +1563,5 @@ export async function runChiefAgenticLoop(deps, {
|
|
|
857
1563
|
if (parsed && typeof parsed.reply === 'string') {
|
|
858
1564
|
parsed.reply = stripToolCallMarkup(parsed.reply)
|
|
859
1565
|
}
|
|
860
|
-
return { ok: Boolean(finalRes && finalRes.ok), llmRes: finalRes, parsed, toolBadges, toolRecords }
|
|
1566
|
+
return { ok: Boolean(finalRes && finalRes.ok), llmRes: finalRes, parsed, toolBadges, toolRecords, pendingApprovals, elevationRequests }
|
|
861
1567
|
}
|