dsh-chief 1.3.0 → 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/chief-executor.js CHANGED
@@ -1,121 +1,98 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import { spawn } from 'node:child_process'
4
-
5
- export const CHIEF_PERMISSION_MODES = ['advisor', 'assistant', 'strategist', 'chief']
6
- export const DEFAULT_CHIEF_PERMISSION_MODE = 'advisor'
7
-
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
4
+ import { performance } from 'node:perf_hooks'
5
+ import {
6
+ CHIEF_PERMISSION_MODES,
7
+ DEFAULT_CHIEF_PERMISSION_MODE,
8
+ CHIEF_PERMISSION_META,
9
+ normalizePermissionMode,
10
+ permissionRank,
11
+ getToolOpClass,
12
+ resolveRoleCapabilities,
13
+ buildCapabilityScope,
14
+ verifyCapabilityScope,
15
+ HUMAN_BOUNDS_CONFIRM_TOKEN,
16
+ safeRealpath,
17
+ isPathInsideWorkspace,
18
+ hasWindowsReservedDeviceName,
19
+ hasForbiddenNtfsAds,
20
+ isSensitiveCredentialPath,
21
+ validateWorkspacePath,
22
+ verifyBoundsWriteAuth,
23
+ decodeEncodedPowerShell,
24
+ normalizeCommandForSecurity,
25
+ splitCompoundCommand,
26
+ extractInlineScriptPayloads,
27
+ analyzeCommand,
28
+ HARD_GUARD_RULE_IDS,
29
+ isDestructiveShellCommand,
30
+ commandTouchesSensitiveCredential,
31
+ checkForbiddenBounds,
32
+ evaluateSafetyGuardHardRules,
33
+ FORBIDDEN_WEAKENING_KEYS,
34
+ validatePolicyPlugin,
35
+ validatePolicyPluginList,
36
+ evaluatePolicyPlugins,
37
+ evaluateChiefPermissionGate,
38
+ evaluateUnifiedToolGate,
39
+ GUARD_WALL_RULE_TYPES,
40
+ GUARD_WALL_SCOPES,
41
+ guardWallsFilePath,
42
+ validateGuardWallInput,
43
+ normalizeGuardWall,
44
+ isGuardWallActiveForCwd,
45
+ listGuardWalls,
46
+ mutateGuardWalls,
47
+ evaluateGuardWalls,
48
+ evaluatePreExecuteDefense,
49
+ redactAuditText,
50
+ } from './safety/index.js'
51
+
52
+ export {
53
+ CHIEF_PERMISSION_MODES,
54
+ DEFAULT_CHIEF_PERMISSION_MODE,
55
+ CHIEF_PERMISSION_META,
56
+ normalizePermissionMode,
57
+ permissionRank,
58
+ getToolOpClass,
59
+ resolveRoleCapabilities,
60
+ buildCapabilityScope,
61
+ verifyCapabilityScope,
62
+ HUMAN_BOUNDS_CONFIRM_TOKEN,
63
+ safeRealpath,
64
+ isPathInsideWorkspace,
65
+ hasWindowsReservedDeviceName,
66
+ hasForbiddenNtfsAds,
67
+ isSensitiveCredentialPath,
68
+ validateWorkspacePath,
69
+ verifyBoundsWriteAuth,
70
+ decodeEncodedPowerShell,
71
+ normalizeCommandForSecurity,
72
+ splitCompoundCommand,
73
+ extractInlineScriptPayloads,
74
+ analyzeCommand,
75
+ HARD_GUARD_RULE_IDS,
76
+ isDestructiveShellCommand,
77
+ commandTouchesSensitiveCredential,
78
+ checkForbiddenBounds,
79
+ evaluateSafetyGuardHardRules,
80
+ FORBIDDEN_WEAKENING_KEYS,
81
+ validatePolicyPlugin,
82
+ validatePolicyPluginList,
83
+ evaluatePolicyPlugins,
84
+ evaluateChiefPermissionGate,
85
+ evaluateUnifiedToolGate,
86
+ GUARD_WALL_RULE_TYPES,
87
+ GUARD_WALL_SCOPES,
88
+ guardWallsFilePath,
89
+ validateGuardWallInput,
90
+ normalizeGuardWall,
91
+ isGuardWallActiveForCwd,
92
+ listGuardWalls,
93
+ mutateGuardWalls,
94
+ evaluateGuardWalls,
95
+ evaluatePreExecuteDefense,
119
96
  }
120
97
 
121
98
  export const CHIEF_TOOLS_PROMPT_GUIDE = [
@@ -259,272 +236,6 @@ function truncateMiddle(text, maxBytes = 12_288) {
259
236
  return s.slice(0, head) + `\n...[已截断 ${s.length - maxBytes} 字符]...\n` + s.slice(-tail)
260
237
  }
261
238
 
262
- function safeRealpath(targetPath) {
263
- try {
264
- return fs.realpathSync.native ? fs.realpathSync.native(targetPath) : fs.realpathSync(targetPath)
265
- } catch {
266
- return path.resolve(targetPath)
267
- }
268
- }
269
-
270
- export function isPathInsideWorkspace(workspaceRoot, targetPath) {
271
- if (!workspaceRoot || !targetPath) return false
272
- const rootAbs = safeRealpath(workspaceRoot)
273
- let probe = path.resolve(rootAbs, targetPath)
274
- if (!fs.existsSync(probe)) {
275
- const parent = path.dirname(probe)
276
- probe = fs.existsSync(parent) ? path.join(safeRealpath(parent), path.basename(probe)) : path.resolve(probe)
277
- } else {
278
- probe = safeRealpath(probe)
279
- }
280
- const cmpRoot = process.platform === 'win32' ? rootAbs.toLowerCase() : rootAbs
281
- const cmpTarget = process.platform === 'win32' ? probe.toLowerCase() : probe
282
- const rel = path.relative(cmpRoot, cmpTarget)
283
- return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
284
- }
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
-
324
- function isSensitiveCredentialPath(filePath) {
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
- }
335
- }
336
- return false
337
- }
338
-
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
- }
359
-
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
- }
385
- }
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)
449
- }
450
-
451
- /**
452
- * 无论当前处于何种权限级别(包括 danger-full-access),都坚决守住用户在看板中设定的禁止红线。
453
- */
454
- export function checkForbiddenBounds(board, actionDesc = '', commandOrPath = '', extraContent = '') {
455
- const forbidden = [
456
- ...((board && board.bounds && Array.isArray(board.bounds.forbidden)) ? board.bounds.forbidden : []),
457
- ...((board && board.pinnedBounds && Array.isArray(board.pinnedBounds.forbidden)) ? board.pinnedBounds.forbidden : []),
458
- ]
459
- if (!forbidden.length) return { blocked: false }
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()
472
-
473
- for (const rule of forbidden) {
474
- const rText = String(rule || '').trim()
475
- if (!rText) continue
476
- const ruleNorm = rText.replace(/\\/g, '/')
477
- const ruleLower = ruleNorm.toLowerCase()
478
-
479
- // 1. 提取反引号或引号内的受禁命令或路径字面量,如 `git push`、`npm publish`、"secret.env"
480
- const quoted = [
481
- ...[...ruleNorm.matchAll(/`([^`]{2,80})`/g)].map(m => m[1]),
482
- ...[...ruleNorm.matchAll(/["'「『]([^"'」』]{2,80})["'」』]/g)].map(m => m[1]),
483
- ].map(s => s.trim().toLowerCase())
484
- for (const token of quoted) {
485
- if (token && haystack.includes(token)) {
486
- return { blocked: true, matchedRule: rText, trigger: token }
487
- }
488
- }
489
-
490
- // 2. 提取不带反引号的文件名、路径片段、点文件或扩展名(如 secret.env、src/auth.js、package.json、.env)
491
- const pathTokens = [...ruleLower.matchAll(/(?:[a-z0-9_.-]+\/[a-z0-9_.\-\/]+|\.[a-z0-9_-]{2,16}|[a-z0-9_-]{2,40}\.[a-z0-9]{1,10})/g)]
492
- .map(m => m[0].trim())
493
- for (const tok of pathTokens) {
494
- if (tok && tok.length >= 3 && haystack.includes(tok)) {
495
- return { blocked: true, matchedRule: rText, trigger: tok }
496
- }
497
- }
498
-
499
- // 3. 匹配常见高危动词组合
500
- const dangerousCmds = [
501
- 'git push',
502
- 'npm publish',
503
- 'git reset --hard',
504
- 'rm -rf',
505
- 'del /f',
506
- 'format ',
507
- 'drop table',
508
- 'drop database',
509
- ]
510
- for (const cmdTok of dangerousCmds) {
511
- if (ruleLower.includes(cmdTok) && haystack.includes(cmdTok)) {
512
- return { blocked: true, matchedRule: rText, trigger: cmdTok }
513
- }
514
- }
515
-
516
- // 4. 若用户直接写了极短裸禁止词(去前缀后 >= 4 字符的命令行或目录标记)
517
- const stripped = ruleLower
518
- .replace(/^(?:严禁|禁止|不得|切勿|不要|不能|不可|不允许|勿|do\s+not|never|forbid)\s*/i, '')
519
- .replace(/^(?:改动|修改|编辑|写入|删除|覆盖|执行|运行|推送|发布|触碰)\s*/i, '')
520
- .trim()
521
- if (stripped.length >= 4 && /^[a-z0-9_.\-\/:\s]{4,64}$/.test(stripped) && haystack.includes(stripped)) {
522
- return { blocked: true, matchedRule: rText, trigger: stripped }
523
- }
524
- }
525
- return { blocked: false }
526
- }
527
-
528
239
  function runSubprocess(command, cwd, timeoutMs = 20_000) {
529
240
  return new Promise((resolve) => {
530
241
  const clampedTimeout = Math.min(45_000, Math.max(2_000, Number(timeoutMs) || 20_000))
@@ -672,174 +383,6 @@ function runRgSearch(rootDir, pattern, maxHits = 30) {
672
383
  })
673
384
  }
674
385
 
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
386
  function displayRelTarget(cwd, rawTarget) {
844
387
  const raw = String(rawTarget || '').trim()
845
388
  if (!raw) return '工作区'
@@ -968,22 +511,28 @@ export function describeControlledOperationMeta(tool, args = {}, cwd = '') {
968
511
  * 用户模式 -> 操作请求 -> 安全卫兵硬性规则 -> 权限判定 -> 执行器 -> 审计日志
969
512
  */
970
513
  export async function executeChiefToolCall(deps, call, execCtx = {}) {
514
+ const startedAt = performance.now()
971
515
  const tool = String(call && (call.tool || call.name) || '').trim()
972
516
  const args = (call && call.args && typeof call.args === 'object') ? call.args : (call && typeof call === 'object' ? call : {})
973
517
  const hasChiefRiskAck = Boolean(execCtx.hasChiefRiskAck)
518
+ const policyPlugins = Array.isArray(execCtx.policyPlugins) ? execCtx.policyPlugins : []
974
519
  const permissionMode = normalizePermissionMode(execCtx.permissionMode, { requireAck: true, hasChiefRiskAck })
975
520
  const cwd = String(execCtx.cwd || process.cwd())
976
521
  const rootId = String(execCtx.rootId || '')
977
522
  const board = execCtx.board || {}
978
523
  const readOnlyToolsOnly = Boolean(execCtx.readOnlyToolsOnly)
979
524
  const approvedOnce = Boolean(execCtx.approvedOnce)
525
+ const capabilityScope = execCtx.capabilityScope || null
980
526
 
981
527
  const writeAudit = (entry) => {
982
528
  if (typeof execCtx.recordAuditFn === 'function') {
983
529
  try {
530
+ const durationMs = Math.max(0, Math.round(performance.now() - startedAt))
984
531
  execCtx.recordAuditFn({
985
532
  mode: permissionMode,
986
533
  tool,
534
+ durationMs,
535
+ summary: redactAuditText(entry.summary || entry.reason || '', 220),
987
536
  by: execCtx.by || 'chief',
988
537
  ...entry,
989
538
  })
@@ -1004,7 +553,7 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
1004
553
 
1005
554
  const opClass = getToolOpClass(tool)
1006
555
  if (readOnlyToolsOnly && opClass !== 'read') {
1007
- writeAudit({ stage: 'read_only_guard', decision: 'denied', operation: tool, target: '', reason: '后台复盘仅允许只读核验', outcome: 'blocked' })
556
+ writeAudit({ stage: 'read_only_guard', rule: 'read_only_guard', decision: 'denied', operation: tool, target: '', reason: '后台复盘仅允许只读核验', outcome: 'blocked' })
1008
557
  return deny(`后台复盘轮次仅允许只读核验工具(${tool} 已跳过)`)
1009
558
  }
1010
559
 
@@ -1014,7 +563,7 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
1014
563
  const resolvedAbsTarget = rawTargetPath ? path.resolve(cwd, rawTargetPath) : ''
1015
564
  const rawCommand = tool === 'run_command' ? String(args.command || args.cmd || '').trim() : ''
1016
565
 
1017
- // Stage 3: 安全卫兵硬性规则(优先于任何权限等级与逐项批准)
566
+ // Stage 3: 安全卫兵硬性规则(优先于任何权限等级、策略插件与逐项批准)
1018
567
  const guardRes = evaluateSafetyGuardHardRules({
1019
568
  tool,
1020
569
  opClass,
@@ -1027,26 +576,128 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
1027
576
  if (guardRes.blocked) {
1028
577
  writeAudit({
1029
578
  stage: 'safety_guard',
579
+ rule: guardRes.rule || 'hard_guard',
1030
580
  decision: 'blocked',
1031
581
  operation: tool,
1032
582
  target: displayRelTarget(cwd, resolvedAbsTarget) || clamp(rawCommand, 80) || tool,
1033
583
  reason: guardRes.reason,
1034
584
  outcome: 'blocked',
1035
585
  })
1036
- return deny(guardRes.reason, guardRes.badge, { blockedBySafetyGuard: true })
586
+ return deny(guardRes.reason, guardRes.badge, { blockedBySafetyGuard: true, rule: guardRes.rule || 'hard_guard' })
1037
587
  }
1038
588
 
1039
- // Stage 4: 四级权限判定
589
+ // Stage 3.5: 动态物理驻墙检验(同样不受 L3 与逐项放行绕过,require_approval_cmd 转为弹窗确认)
590
+ const wallRes = evaluateGuardWalls({
591
+ tool,
592
+ opClass,
593
+ targetPath: resolvedAbsTarget,
594
+ command: rawCommand,
595
+ args,
596
+ cwd,
597
+ })
598
+ if (wallRes.decision === 'block') {
599
+ writeAudit({
600
+ stage: 'guard_wall',
601
+ rule: wallRes.rule || 'guard_wall_block',
602
+ decision: 'blocked',
603
+ operation: tool,
604
+ target: displayRelTarget(cwd, resolvedAbsTarget) || clamp(rawCommand, 80) || tool,
605
+ reason: wallRes.reason,
606
+ outcome: 'blocked',
607
+ })
608
+ return deny(wallRes.reason, wallRes.badge || '🧱 物理墙拦截', {
609
+ blockedByGuardWall: true,
610
+ blockedBySafetyGuard: true,
611
+ rule: wallRes.rule || 'guard_wall_block',
612
+ wallId: wallRes.wallId,
613
+ })
614
+ }
615
+ if (wallRes.decision === 'require_approval' && !approvedOnce) {
616
+ const meta = describeControlledOperationMeta(tool, args, cwd)
617
+ const computedScope = buildCapabilityScope({ kind: 'tool', tool, args, cwd })
618
+ const approvalObj = typeof execCtx.queueApprovalFn === 'function'
619
+ ? await execCtx.queueApprovalFn({
620
+ category: meta.category,
621
+ operationLabel: meta.operationLabel,
622
+ targetLabel: meta.targetLabel,
623
+ reason: wallRes.reason,
624
+ impact: meta.impact,
625
+ preview: meta.preview,
626
+ kind: 'tool',
627
+ capabilityScope: computedScope,
628
+ payload: { tool, args: { ...args }, cwd, rootId, sessionId: execCtx.sessionId || rootId },
629
+ by: execCtx.by || 'guard_wall',
630
+ })
631
+ : null
632
+ writeAudit({
633
+ stage: 'guard_wall',
634
+ rule: wallRes.rule || 'guard_wall_require_approval',
635
+ decision: 'pending_approval',
636
+ operation: meta.operationLabel,
637
+ target: meta.targetLabel,
638
+ reason: wallRes.reason,
639
+ outcome: 'pending',
640
+ })
641
+ return {
642
+ tool,
643
+ ok: false,
644
+ pendingApproval: true,
645
+ approvalId: (approvalObj && approvalObj.id) || '',
646
+ approval: approvalObj || null,
647
+ error: `${wallRes.reason}。已为您弹出「操作授权请求」弹窗,等待点击「允许本次操作」。`,
648
+ badge: wallRes.badge || '🧱 物理墙待确认',
649
+ }
650
+ }
651
+
652
+ // Stage 4: 四级权限 + capabilities + Policy Plugin + 单次作用域判定
1040
653
  const gateRes = evaluateChiefPermissionGate({
1041
654
  permissionMode,
1042
655
  hasChiefRiskAck,
1043
656
  opClass,
1044
657
  tool,
1045
658
  approvedOnce,
659
+ capabilityScope,
660
+ actualRequest: { kind: 'tool', tool, args, cwd },
661
+ policyPlugins,
662
+ targetPath: resolvedAbsTarget,
663
+ command: rawCommand,
664
+ cwd,
1046
665
  })
666
+ if (gateRes.decision === 'deny_policy_plugin') {
667
+ writeAudit({
668
+ stage: 'policy_plugin',
669
+ rule: gateRes.rule || 'policy_plugin',
670
+ decision: 'blocked',
671
+ operation: tool,
672
+ target: rawTargetPath || clamp(rawCommand, 60) || tool,
673
+ reason: gateRes.error,
674
+ outcome: 'blocked',
675
+ })
676
+ return deny(gateRes.error, gateRes.badge, {
677
+ blockedByPolicyPlugin: true,
678
+ pluginId: gateRes.pluginId || '',
679
+ rule: gateRes.rule || 'policy_plugin',
680
+ })
681
+ }
682
+ if (gateRes.decision === 'deny_scope_mismatch') {
683
+ writeAudit({
684
+ stage: 'scope_guard',
685
+ rule: gateRes.rule || 'capability_scope_mismatch',
686
+ decision: 'rejected',
687
+ operation: tool,
688
+ target: rawTargetPath || clamp(rawCommand, 60) || tool,
689
+ reason: gateRes.error,
690
+ outcome: 'rejected',
691
+ })
692
+ return deny(gateRes.error, gateRes.badge, {
693
+ deniedByScopeMismatch: true,
694
+ rule: gateRes.rule || 'capability_scope_mismatch',
695
+ })
696
+ }
1047
697
  if (gateRes.decision === 'deny_mode' || gateRes.decision === 'deny_unacknowledged_l3') {
1048
698
  writeAudit({
1049
699
  stage: 'permission_gate',
700
+ rule: gateRes.rule || gateRes.decision,
1050
701
  decision: gateRes.decision,
1051
702
  operation: tool,
1052
703
  target: rawTargetPath || clamp(rawCommand, 60) || String(args.agent || args.op || tool),
@@ -1061,6 +712,7 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
1061
712
  }
1062
713
  if (gateRes.decision === 'require_approval') {
1063
714
  const meta = describeControlledOperationMeta(tool, args, cwd)
715
+ const computedScope = buildCapabilityScope({ kind: 'tool', tool, args, cwd })
1064
716
  const approvalObj = typeof execCtx.queueApprovalFn === 'function'
1065
717
  ? await execCtx.queueApprovalFn({
1066
718
  category: meta.category,
@@ -1070,12 +722,14 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
1070
722
  impact: meta.impact,
1071
723
  preview: meta.preview,
1072
724
  kind: 'tool',
725
+ capabilityScope: computedScope,
1073
726
  payload: { tool, args: { ...args }, cwd, rootId, sessionId: execCtx.sessionId || rootId },
1074
727
  by: execCtx.by || 'chief',
1075
728
  })
1076
729
  : null
1077
730
  writeAudit({
1078
731
  stage: 'permission_gate',
732
+ rule: gateRes.rule || 'require_approval',
1079
733
  decision: 'pending_approval',
1080
734
  operation: meta.operationLabel,
1081
735
  target: meta.targetLabel,
@@ -1088,15 +742,41 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
1088
742
  pendingApproval: true,
1089
743
  approvalId: (approvalObj && approvalObj.id) || '',
1090
744
  approval: approvalObj || null,
1091
- error: `当前处于「L2 · 参谋模式」,操作「${meta.operationLabel} → ${meta.targetLabel}」已提交操作授权弹窗,等待用户点击「允许本次操作」。`,
745
+ error: `当前处于「${CHIEF_PERMISSION_META[gateRes.mode]?.level || 'L2'} · ${CHIEF_PERMISSION_META[gateRes.mode]?.title || '参谋模式'}」,操作「${meta.operationLabel} → ${meta.targetLabel}」已提交操作授权弹窗,等待用户点击「允许本次操作」。`,
1092
746
  badge: `🛡️ 待确认 ${clamp(meta.targetLabel, 18)}`,
1093
747
  }
1094
748
  }
1095
749
 
1096
- // Stage 5: 执行器
750
+ // Stage 5: 执行器(包含写入路径能力前缀二次确认)
751
+ const allowedWritePrefixes = gateRes && gateRes.capabilities && Array.isArray(gateRes.capabilities.fsWritePrefixes)
752
+ ? gateRes.capabilities.fsWritePrefixes
753
+ : null
754
+ if ((tool === 'write_file' || tool === 'edit_file') && rawTargetPath) {
755
+ const writePathCheck = validateWorkspacePath(cwd, resolvedAbsTarget, {
756
+ mode: 'write',
757
+ allowedSubPrefixes: allowedWritePrefixes,
758
+ })
759
+ if (writePathCheck.blocked) {
760
+ writeAudit({
761
+ stage: writePathCheck.stage || 'safety_guard',
762
+ rule: writePathCheck.rule || 'workspace_write_denied',
763
+ decision: 'blocked',
764
+ operation: tool,
765
+ target: displayRelTarget(cwd, resolvedAbsTarget),
766
+ reason: writePathCheck.reason,
767
+ outcome: 'blocked',
768
+ })
769
+ return deny(writePathCheck.reason, writePathCheck.badge, {
770
+ blockedBySafetyGuard: writePathCheck.stage === 'safety_guard',
771
+ rule: writePathCheck.rule,
772
+ })
773
+ }
774
+ }
775
+
1097
776
  const finish = (res, opLabel, targetLabel) => {
1098
777
  writeAudit({
1099
778
  stage: 'executor',
779
+ rule: approvedOnce ? 'approved_once' : 'role_allow',
1100
780
  decision: approvedOnce ? 'executed_approved' : 'executed',
1101
781
  operation: opLabel || tool,
1102
782
  target: targetLabel || '',
@@ -1409,10 +1089,12 @@ export async function runChiefAgenticLoop(deps, {
1409
1089
  allowTextFallbackOnVisionMiss = false,
1410
1090
  permissionMode = DEFAULT_CHIEF_PERMISSION_MODE,
1411
1091
  hasChiefRiskAck = false,
1092
+ policyPlugins = [],
1412
1093
  board = null,
1413
1094
  maxSteps = 4,
1414
1095
  readOnlyToolsOnly = false,
1415
1096
  disableTools = false,
1097
+ lazyDeferWorkspaceWritesToLead = false,
1416
1098
  callLlmFn,
1417
1099
  extractJsonFn,
1418
1100
  upsertArchiveFn,
@@ -1490,12 +1172,54 @@ export async function runChiefAgenticLoop(deps, {
1490
1172
  ranToolsOnLastStep = true
1491
1173
  const stepOutputs = []
1492
1174
  for (const c of calls) {
1175
+ const cToolName = String(c && (c.tool || c.name) || '').trim()
1176
+ if (
1177
+ lazyDeferWorkspaceWritesToLead
1178
+ && (cToolName === 'write_file' || cToolName === 'edit_file' || cToolName === 'run_command')
1179
+ ) {
1180
+ const preDef = evaluatePreExecuteDefense({
1181
+ tool: cToolName,
1182
+ args: (c && c.args && typeof c.args === 'object') ? c.args : {},
1183
+ cwd,
1184
+ board,
1185
+ })
1186
+ if (!preDef || preDef.decision !== 'deny') {
1187
+ if (typeof recordAuditFn === 'function') {
1188
+ try {
1189
+ recordAuditFn({
1190
+ mode: perm,
1191
+ stage: 'lazy_intervention',
1192
+ rule: 'lead_first_defer',
1193
+ decision: 'deferred_to_lead',
1194
+ operation: cToolName,
1195
+ target: clamp(String((c.args && (c.args.path || c.args.command || c.args.cmd)) || cToolName), 80),
1196
+ reason: '懒介入机制生效:主对话在线且用户未指定参谋长亲自操作,改为派发 @lead 执行请求',
1197
+ outcome: 'deferred',
1198
+ by: 'chief',
1199
+ })
1200
+ } catch {}
1201
+ }
1202
+ const deferRes = {
1203
+ tool: cToolName,
1204
+ ok: false,
1205
+ denied: true,
1206
+ deferredByLazyIntervention: true,
1207
+ badge: '🤝 懒介入转主对话',
1208
+ error: '懒介入机制生效:当前主对话 (@lead) 在线可用且用户未指定参谋长亲自操刀,已遏制直接改动工作区或跑终端命令。请去掉工作区 toolCalls,改为在最终 JSON 的 relays 中向 target="lead" 下发结构化执行请求!',
1209
+ }
1210
+ toolRecords.push({ step: step + 1, call: c, result: deferRes })
1211
+ if (!toolBadges.includes(deferRes.badge)) toolBadges.push(deferRes.badge)
1212
+ stepOutputs.push({ tool: cToolName, args: c.args || {}, result: deferRes })
1213
+ continue
1214
+ }
1215
+ }
1493
1216
  const execRes = await executeChiefToolCall(deps, c, {
1494
1217
  rootId,
1495
1218
  sessionId: sessionId || rootId,
1496
1219
  cwd,
1497
1220
  permissionMode: perm,
1498
1221
  hasChiefRiskAck,
1222
+ policyPlugins,
1499
1223
  board,
1500
1224
  readOnlyToolsOnly,
1501
1225
  upsertArchiveFn,