dsh-chief 1.0.0 → 1.2.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 +72 -0
- package/README.en.md +113 -64
- package/README.md +124 -89
- package/archives.js +1999 -165
- package/auto-continue.js +627 -0
- package/chief-executor.js +861 -0
- package/chief.js +4751 -475
- package/client.js +12015 -6611
- package/digest.js +67 -21
- package/handoff.js +3 -3
- package/index.js +1780 -138
- package/package.json +7 -3
|
@@ -0,0 +1,861 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { spawn } from 'node:child_process'
|
|
4
|
+
|
|
5
|
+
export const CHIEF_PERMISSION_MODES = ['read-only', 'workspace-write', 'danger-full-access', 'auto-review']
|
|
6
|
+
export const DEFAULT_CHIEF_PERMISSION_MODE = 'danger-full-access'
|
|
7
|
+
|
|
8
|
+
export function normalizePermissionMode(raw) {
|
|
9
|
+
const v = String(raw || '').trim()
|
|
10
|
+
return CHIEF_PERMISSION_MODES.includes(v) ? v : DEFAULT_CHIEF_PERMISSION_MODE
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export const CHIEF_TOOLS_PROMPT_GUIDE = [
|
|
14
|
+
'【参谋长实权工具协议(`toolCalls`)】',
|
|
15
|
+
'你默认拥有最高「完全权限 (`danger-full-access`)」,绝不只是传话筒!当需要查证代码、修改文件、跑命令/测试验证、维护档案、立刻压缩或直接派发/插话/中断子代理时,可在输出 JSON 中附加 `"toolCalls"` 数组(每轮最多 4 项,系统将立即执行并把真实输出回传给你,直到你给出最终答复 JSON 且不再包含 `"toolCalls"`):',
|
|
16
|
+
'- `read_file`: `{ "path": "相对或绝对路径", "startLine": 1, "endLine": 180 }`',
|
|
17
|
+
'- `list_dir`: `{ "path": "可选目录路径,默认当前工作区" }`',
|
|
18
|
+
'- `search_files`: `{ "pattern": "正则或关键词", "path": "可选目录", "maxHits": 30 }`',
|
|
19
|
+
'- `write_file`: `{ "path": "文件路径", "content": "完整新文件内容" }`',
|
|
20
|
+
'- `edit_file`: `{ "path": "文件路径", "target": "精确旧文本", "replacement": "精确新文本" }`',
|
|
21
|
+
'- `run_command`: `{ "command": "终端命令", "cwd": "可选工作目录", "timeoutMs": 20000 }`',
|
|
22
|
+
'- `subagent_dispatch`: `{ "taskId": "可选已有任务ID", "title": "无taskId时自动建卡标题", "agent": "子代理名", "prompt": "委派指令", "preset": "可选", "force": false }`',
|
|
23
|
+
'- `subagent_steer`: `{ "agent": "子代理名", "taskId": "可选", "message": "纠偏指令" }`',
|
|
24
|
+
'- `subagent_interrupt`: `{ "agent": "子代理名", "taskId": "可选" }`',
|
|
25
|
+
'- `archive_write`: `{ "vaultScope": "session|global", "folder": "coords|case|spec|ops|plan|inbox", "title": "标题", "summary": "摘要", "body": "正文", "tags": [] }`',
|
|
26
|
+
'- `session_compact`: `{ "reason": "触发原因" }`',
|
|
27
|
+
'注意:',
|
|
28
|
+
'1) 若需调用工具,请输出合法 JSON `{ "toolCalls": [...], "reply": "当前排查中的简要进度" }`。**严禁**输出 `<|DSML|...>`、`< | | DSML | | ...>`、`<|DSML|...>`、`<function_calls>` 或 `<invoke>` 等原生 XML 工具标记!',
|
|
29
|
+
'2) **小白状态/步骤追问禁扫目录铁律**:当用户只是问「主对话现在在做什么」「处于什么步骤」「当前进度如何」「到哪一步了」「卡在哪」时,提示词中的【实时对话流现场快照】、【核心目标】与【小任务板/任务列表】已经包含完整状态,**严禁调用 `run_command` 或 `list_dir` 扫描本地磁盘目录**,请直接输出最终 JSON `{ "reply": "…" }` 用通俗人话回答!',
|
|
30
|
+
'3) 工具返回结果回传给你后,若已完成查验与执行,请输出最终 JSON(去掉 `"toolCalls"`),并在 `reply` 中以实测事实作答;任何权限或红线拦截时如实汇报,绝不伪造输出。',
|
|
31
|
+
].join('\n')
|
|
32
|
+
|
|
33
|
+
const DSML_PREFIX = '(?:[\\s||¦│┃]*DSML[\\s||¦│┃]*)'
|
|
34
|
+
const DSML_OPEN_RE = new RegExp(`<${DSML_PREFIX}(?:calls|invoke)\\b`, 'i')
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Strip DeepSeek DSML / XML tool-call markup (`<|DSML|calls>`, `<||DSML|| calls>`,
|
|
38
|
+
* `< | | DSML | | ...>`, `<function_calls>`, `<invoke>`, `<tool_call>`, or unclosed tails)
|
|
39
|
+
* so raw internal tool syntax NEVER leaks into Chief UI or user replies.
|
|
40
|
+
*/
|
|
41
|
+
export function stripToolCallMarkup(rawText) {
|
|
42
|
+
let s = String(rawText || '')
|
|
43
|
+
if (!s) return ''
|
|
44
|
+
// 1) Closed DSML blocks (ASCII |, fullwidth |, repeated bars, optional whitespace)
|
|
45
|
+
s = s.replace(new RegExp(`<${DSML_PREFIX}calls\\b[^>]*>[\\s\\S]*?</${DSML_PREFIX}calls\\s*>`, 'gi'), '\n')
|
|
46
|
+
s = s.replace(new RegExp(`<${DSML_PREFIX}invoke\\b[^>]*>[\\s\\S]*?</${DSML_PREFIX}invoke\\s*>`, 'gi'), '\n')
|
|
47
|
+
// 2) Generic XML tool-call envelopes
|
|
48
|
+
s = s.replace(/<function_calls\b[^>]*>[\s\S]*?<\/function_calls\s*>/gi, '\n')
|
|
49
|
+
s = s.replace(/<tool_call\b[^>]*>[\s\S]*?<\/tool_call\s*>/gi, '\n')
|
|
50
|
+
s = s.replace(/<invoke\b[^>]*>[\s\S]*?<\/invoke\s*>/gi, '\n')
|
|
51
|
+
// 3) Unclosed / truncated DSML or XML tool-call tails
|
|
52
|
+
s = s.replace(new RegExp(`<${DSML_PREFIX}(?:calls|invoke|parameter)\\b[\\s\\S]*$`, 'gi'), '')
|
|
53
|
+
s = s.replace(/<(?:function_calls|tool_call|invoke)\b[\s\S]*$/gi, '')
|
|
54
|
+
// 4) Leftover single DSML tags
|
|
55
|
+
s = s.replace(new RegExp(`</?${DSML_PREFIX}[a-z_-]*\\b[^>]*>`, 'gi'), '')
|
|
56
|
+
// 5) Stray standalone "toolCalls" JSON object envelope if the entire text is just raw tool scheduling
|
|
57
|
+
const trimmed = s.trim()
|
|
58
|
+
if (/^\s*\{[\s\S]*"toolCalls"\s*:\s*\[[\s\S]*\}\s*$/i.test(trimmed)) {
|
|
59
|
+
try {
|
|
60
|
+
const obj = JSON.parse(trimmed)
|
|
61
|
+
if (obj && typeof obj === 'object' && Array.isArray(obj.toolCalls) && typeof obj.reply === 'string') {
|
|
62
|
+
s = obj.reply
|
|
63
|
+
} else {
|
|
64
|
+
s = ''
|
|
65
|
+
}
|
|
66
|
+
} catch {
|
|
67
|
+
if (!/[\u4e00-\u9fa5]{4,}/.test(trimmed)) s = ''
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return s.replace(/\n{3,}/g, '\n\n').trim()
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Fallback parser when a DeepSeek model emits native DSML tool invocations
|
|
75
|
+
* (`< | | DSML | | invoke name="list_dir">...`) instead of JSON `"toolCalls"`.
|
|
76
|
+
*/
|
|
77
|
+
export function parseDsmlToolCalls(rawText) {
|
|
78
|
+
const s = String(rawText || '')
|
|
79
|
+
if (!s || !DSML_OPEN_RE.test(s)) return []
|
|
80
|
+
const calls = []
|
|
81
|
+
const invokeRe = new RegExp(
|
|
82
|
+
`<${DSML_PREFIX}invoke\\s+name=["']([^"']+)["'][^>]*>([\\s\\S]*?)(?:</${DSML_PREFIX}invoke\\s*>|(?=<${DSML_PREFIX}invoke\\b|</${DSML_PREFIX}calls\\s*>|$))`,
|
|
83
|
+
'gi',
|
|
84
|
+
)
|
|
85
|
+
let m
|
|
86
|
+
while ((m = invokeRe.exec(s)) !== null && calls.length < 4) {
|
|
87
|
+
let toolName = String(m[1] || '').trim()
|
|
88
|
+
const body = String(m[2] || '')
|
|
89
|
+
const paramRe = new RegExp(
|
|
90
|
+
`<${DSML_PREFIX}parameter\\s+name=["']([^"']+)["']([^>]*)>([\\s\\S]*?)(?:</${DSML_PREFIX}parameter\\s*>|(?=<${DSML_PREFIX}parameter\\b|</${DSML_PREFIX}(?:invoke|calls)\\s*>|$))`,
|
|
91
|
+
'gi',
|
|
92
|
+
)
|
|
93
|
+
const rawParams = {}
|
|
94
|
+
let pm
|
|
95
|
+
while ((pm = paramRe.exec(body)) !== null) {
|
|
96
|
+
const pName = String(pm[1] || '').trim()
|
|
97
|
+
const attrs = String(pm[2] || '')
|
|
98
|
+
let pVal = String(pm[3] || '').trim()
|
|
99
|
+
const isStr = /string\s*=\s*["']true["']/i.test(attrs)
|
|
100
|
+
if (!isStr && (pVal.startsWith('{') || pVal.startsWith('[') || pVal === 'true' || pVal === 'false' || /^-?\d+(?:\.\d+)?$/.test(pVal))) {
|
|
101
|
+
try {
|
|
102
|
+
pVal = JSON.parse(pVal)
|
|
103
|
+
} catch {}
|
|
104
|
+
}
|
|
105
|
+
if (pName) rawParams[pName] = pVal
|
|
106
|
+
}
|
|
107
|
+
if (typeof rawParams.tool === 'string' && rawParams.tool.trim()) {
|
|
108
|
+
toolName = rawParams.tool.trim()
|
|
109
|
+
}
|
|
110
|
+
let finalArgs = {}
|
|
111
|
+
if (rawParams.args && typeof rawParams.args === 'object' && !Array.isArray(rawParams.args)) {
|
|
112
|
+
finalArgs = rawParams.args
|
|
113
|
+
} else if (typeof rawParams.args === 'string' && rawParams.args.trim().startsWith('{')) {
|
|
114
|
+
try {
|
|
115
|
+
const parsedArgs = JSON.parse(rawParams.args)
|
|
116
|
+
if (parsedArgs && typeof parsedArgs === 'object') finalArgs = parsedArgs
|
|
117
|
+
} catch {
|
|
118
|
+
finalArgs = { ...rawParams }
|
|
119
|
+
}
|
|
120
|
+
} else {
|
|
121
|
+
for (const [k, v] of Object.entries(rawParams)) {
|
|
122
|
+
if (k === 'tool' || k === 'args') continue
|
|
123
|
+
finalArgs[k] = v
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (toolName) calls.push({ tool: toolName, args: finalArgs })
|
|
127
|
+
}
|
|
128
|
+
return calls
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function clamp(text, maxLen = 200) {
|
|
132
|
+
const s = String(text || '').trim()
|
|
133
|
+
return s.length > maxLen ? s.slice(0, maxLen) + '...' : s
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function truncateMiddle(text, maxBytes = 12_288) {
|
|
137
|
+
const s = String(text || '')
|
|
138
|
+
if (s.length <= maxBytes) return s
|
|
139
|
+
const head = Math.floor(maxBytes * 0.65)
|
|
140
|
+
const tail = maxBytes - head
|
|
141
|
+
return s.slice(0, head) + `\n...[已截断 ${s.length - maxBytes} 字符]...\n` + s.slice(-tail)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function safeRealpath(targetPath) {
|
|
145
|
+
try {
|
|
146
|
+
return fs.realpathSync.native ? fs.realpathSync.native(targetPath) : fs.realpathSync(targetPath)
|
|
147
|
+
} catch {
|
|
148
|
+
return path.resolve(targetPath)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function isPathInsideWorkspace(workspaceRoot, targetPath) {
|
|
153
|
+
if (!workspaceRoot || !targetPath) return false
|
|
154
|
+
const rootAbs = safeRealpath(workspaceRoot)
|
|
155
|
+
let probe = path.resolve(rootAbs, targetPath)
|
|
156
|
+
if (!fs.existsSync(probe)) {
|
|
157
|
+
const parent = path.dirname(probe)
|
|
158
|
+
probe = fs.existsSync(parent) ? path.join(safeRealpath(parent), path.basename(probe)) : path.resolve(probe)
|
|
159
|
+
} else {
|
|
160
|
+
probe = safeRealpath(probe)
|
|
161
|
+
}
|
|
162
|
+
const cmpRoot = process.platform === 'win32' ? rootAbs.toLowerCase() : rootAbs
|
|
163
|
+
const cmpTarget = process.platform === 'win32' ? probe.toLowerCase() : probe
|
|
164
|
+
const rel = path.relative(cmpRoot, cmpTarget)
|
|
165
|
+
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function isSensitiveCredentialPath(filePath) {
|
|
169
|
+
const base = path.basename(String(filePath || '')).toLowerCase()
|
|
170
|
+
const normalized = String(filePath || '').replace(/\\/g, '/').toLowerCase()
|
|
171
|
+
if (base === '.env' || base.startsWith('.env.') || base === '.credentials.yaml' || base.startsWith('.credentials.')) {
|
|
172
|
+
return true
|
|
173
|
+
}
|
|
174
|
+
if (/(?:id_rsa|id_ed25519|id_dsa|\.pem$|\.p12$|\.pfx$|credentials\.json$|secrets?\.(?:json|ya?ml)$)/.test(normalized)) {
|
|
175
|
+
return true
|
|
176
|
+
}
|
|
177
|
+
return false
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const READ_ONLY_COMMAND_PATTERNS = [
|
|
181
|
+
/^\s*git\s+(?:status|diff|log|rev-parse|branch|show|tag|remote\s+-v)\b/i,
|
|
182
|
+
/^\s*node\s+(?:--check|-v|--version)\b/i,
|
|
183
|
+
/^\s*(?:python|python3)\s+(?:--version|-V|-m\s+py_compile)\b/i,
|
|
184
|
+
/^\s*(?:rg|grep|findstr|dir|ls|cat|type|pwd|whoami|echo|where|which|Get-ChildItem|Get-Content|Select-String|Get-Location)\b/i,
|
|
185
|
+
]
|
|
186
|
+
|
|
187
|
+
function isReadOnlyShellCommand(command) {
|
|
188
|
+
const cmd = String(command || '').trim()
|
|
189
|
+
if (!cmd) return false
|
|
190
|
+
if (/[><`]|;\s*\S|\&\&|\|\||\b(?:rm|del|erase|rmdir|Remove-Item|Move-Item|Copy-Item|Set-Content|Add-Content|Out-File|mv|cp|mkdir|npm\s+install|pnpm\s+add|git\s+(?:push|commit|reset|clean|checkout|add|merge|rebase))\b/i.test(cmd)) {
|
|
191
|
+
return false
|
|
192
|
+
}
|
|
193
|
+
return READ_ONLY_COMMAND_PATTERNS.some(re => re.test(cmd))
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* 无论当前处于何种权限级别(包括 danger-full-access),都坚决守住用户在看板中设定的禁止红线。
|
|
198
|
+
*/
|
|
199
|
+
export function checkForbiddenBounds(board, actionDesc = '', commandOrPath = '') {
|
|
200
|
+
const forbidden = [
|
|
201
|
+
...((board && board.bounds && Array.isArray(board.bounds.forbidden)) ? board.bounds.forbidden : []),
|
|
202
|
+
...((board && board.pinnedBounds && Array.isArray(board.pinnedBounds.forbidden)) ? board.pinnedBounds.forbidden : []),
|
|
203
|
+
]
|
|
204
|
+
if (!forbidden.length) return { blocked: false }
|
|
205
|
+
const haystack = `${actionDesc} ${commandOrPath}`.replace(/\\/g, '/').toLowerCase()
|
|
206
|
+
|
|
207
|
+
for (const rule of forbidden) {
|
|
208
|
+
const rText = String(rule || '').trim()
|
|
209
|
+
if (!rText) continue
|
|
210
|
+
const ruleNorm = rText.replace(/\\/g, '/')
|
|
211
|
+
const ruleLower = ruleNorm.toLowerCase()
|
|
212
|
+
|
|
213
|
+
// 1. 提取反引号或引号内的受禁命令或路径字面量,如 `git push`、`npm publish`、"secret.env"
|
|
214
|
+
const quoted = [
|
|
215
|
+
...[...ruleNorm.matchAll(/`([^`]{2,80})`/g)].map(m => m[1]),
|
|
216
|
+
...[...ruleNorm.matchAll(/["'「『]([^"'」』]{2,80})["'」』]/g)].map(m => m[1]),
|
|
217
|
+
].map(s => s.trim().toLowerCase())
|
|
218
|
+
for (const token of quoted) {
|
|
219
|
+
if (token && haystack.includes(token)) {
|
|
220
|
+
return { blocked: true, matchedRule: rText, trigger: token }
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// 2. 提取不带反引号的文件名、路径片段、点文件或扩展名(如 secret.env、src/auth.js、package.json、.env)
|
|
225
|
+
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)]
|
|
226
|
+
.map(m => m[0].trim())
|
|
227
|
+
for (const tok of pathTokens) {
|
|
228
|
+
if (tok && tok.length >= 3 && haystack.includes(tok)) {
|
|
229
|
+
return { blocked: true, matchedRule: rText, trigger: tok }
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// 3. 匹配常见高危动词组合
|
|
234
|
+
const dangerousCmds = [
|
|
235
|
+
'git push',
|
|
236
|
+
'npm publish',
|
|
237
|
+
'git reset --hard',
|
|
238
|
+
'rm -rf',
|
|
239
|
+
'del /f',
|
|
240
|
+
'format ',
|
|
241
|
+
'drop table',
|
|
242
|
+
'drop database',
|
|
243
|
+
]
|
|
244
|
+
for (const cmdTok of dangerousCmds) {
|
|
245
|
+
if (ruleLower.includes(cmdTok) && haystack.includes(cmdTok)) {
|
|
246
|
+
return { blocked: true, matchedRule: rText, trigger: cmdTok }
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// 4. 若用户直接写了极短裸禁止词(去前缀后 >= 4 字符的命令行或目录标记)
|
|
251
|
+
const stripped = ruleLower
|
|
252
|
+
.replace(/^(?:严禁|禁止|不得|切勿|不要|不能|不可|不允许|勿|do\s+not|never|forbid)\s*/i, '')
|
|
253
|
+
.replace(/^(?:改动|修改|编辑|写入|删除|覆盖|执行|运行|推送|发布|触碰)\s*/i, '')
|
|
254
|
+
.trim()
|
|
255
|
+
if (stripped.length >= 4 && /^[a-z0-9_.\-\/:\s]{4,64}$/.test(stripped) && haystack.includes(stripped)) {
|
|
256
|
+
return { blocked: true, matchedRule: rText, trigger: stripped }
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return { blocked: false }
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function runSubprocess(command, cwd, timeoutMs = 20_000) {
|
|
263
|
+
return new Promise((resolve) => {
|
|
264
|
+
const clampedTimeout = Math.min(45_000, Math.max(2_000, Number(timeoutMs) || 20_000))
|
|
265
|
+
const isWin = process.platform === 'win32'
|
|
266
|
+
const file = isWin ? 'powershell.exe' : 'sh'
|
|
267
|
+
const args = isWin
|
|
268
|
+
? ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', command]
|
|
269
|
+
: ['-lc', command]
|
|
270
|
+
let stdout = ''
|
|
271
|
+
let stderr = ''
|
|
272
|
+
let settled = false
|
|
273
|
+
let timedOut = false
|
|
274
|
+
|
|
275
|
+
let child
|
|
276
|
+
try {
|
|
277
|
+
child = spawn(file, args, { cwd, windowsHide: true })
|
|
278
|
+
} catch (err) {
|
|
279
|
+
resolve({ ok: false, exitCode: -1, stdout: '', stderr: String(err && err.message ? err.message : err), timedOut: false })
|
|
280
|
+
return
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const timer = setTimeout(() => {
|
|
284
|
+
timedOut = true
|
|
285
|
+
try { child.kill('SIGTERM') } catch {}
|
|
286
|
+
setTimeout(() => { try { child.kill('SIGKILL') } catch {} }, 800).unref?.()
|
|
287
|
+
}, clampedTimeout)
|
|
288
|
+
|
|
289
|
+
child.stdout?.on('data', chunk => {
|
|
290
|
+
if (stdout.length < 32_768) stdout += String(chunk)
|
|
291
|
+
})
|
|
292
|
+
child.stderr?.on('data', chunk => {
|
|
293
|
+
if (stderr.length < 32_768) stderr += String(chunk)
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
child.on('error', err => {
|
|
297
|
+
if (settled) return
|
|
298
|
+
settled = true
|
|
299
|
+
clearTimeout(timer)
|
|
300
|
+
resolve({
|
|
301
|
+
ok: false,
|
|
302
|
+
exitCode: -1,
|
|
303
|
+
stdout: truncateMiddle(stdout),
|
|
304
|
+
stderr: truncateMiddle(stderr + '\n' + String(err && err.message ? err.message : err)),
|
|
305
|
+
timedOut,
|
|
306
|
+
})
|
|
307
|
+
})
|
|
308
|
+
|
|
309
|
+
child.on('close', code => {
|
|
310
|
+
if (settled) return
|
|
311
|
+
settled = true
|
|
312
|
+
clearTimeout(timer)
|
|
313
|
+
resolve({
|
|
314
|
+
ok: code === 0 && !timedOut,
|
|
315
|
+
exitCode: typeof code === 'number' ? code : -1,
|
|
316
|
+
stdout: truncateMiddle(stdout.trim()),
|
|
317
|
+
stderr: truncateMiddle(stderr.trim()),
|
|
318
|
+
timedOut,
|
|
319
|
+
})
|
|
320
|
+
})
|
|
321
|
+
})
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function searchFilesFallbackNode(rootDir, pattern, maxHits = 30) {
|
|
325
|
+
const hits = []
|
|
326
|
+
let re = null
|
|
327
|
+
try {
|
|
328
|
+
re = new RegExp(pattern, 'i')
|
|
329
|
+
} catch {
|
|
330
|
+
re = null
|
|
331
|
+
}
|
|
332
|
+
const needle = String(pattern || '').toLowerCase()
|
|
333
|
+
const skipDirs = new Set(['node_modules', '.git', '.next', 'dist', 'build', '.dsh', '.cache'])
|
|
334
|
+
|
|
335
|
+
const walk = (dir, depth = 0) => {
|
|
336
|
+
if (hits.length >= maxHits || depth > 6) return
|
|
337
|
+
let entries = []
|
|
338
|
+
try {
|
|
339
|
+
entries = fs.readdirSync(dir, { withFileTypes: true })
|
|
340
|
+
} catch {
|
|
341
|
+
return
|
|
342
|
+
}
|
|
343
|
+
for (const ent of entries) {
|
|
344
|
+
if (hits.length >= maxHits) break
|
|
345
|
+
const full = path.join(dir, ent.name)
|
|
346
|
+
if (ent.isDirectory()) {
|
|
347
|
+
if (!skipDirs.has(ent.name)) walk(full, depth + 1)
|
|
348
|
+
} else if (ent.isFile()) {
|
|
349
|
+
try {
|
|
350
|
+
const st = fs.statSync(full)
|
|
351
|
+
if (st.size > 512 * 1024) continue
|
|
352
|
+
const content = fs.readFileSync(full, 'utf8')
|
|
353
|
+
if (content.includes('\u0000')) continue
|
|
354
|
+
const lines = content.split(/\r?\n/)
|
|
355
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
356
|
+
const line = lines[i]
|
|
357
|
+
const matched = re ? re.test(line) : line.toLowerCase().includes(needle)
|
|
358
|
+
if (matched) {
|
|
359
|
+
hits.push(`${path.relative(rootDir, full) || ent.name}:${i + 1}: ${clamp(line, 180)}`)
|
|
360
|
+
if (hits.length >= maxHits) break
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
} catch {}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
walk(rootDir, 0)
|
|
368
|
+
return hits
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function runRgSearch(rootDir, pattern, maxHits = 30) {
|
|
372
|
+
return new Promise((resolve) => {
|
|
373
|
+
const child = spawn('rg', ['-n', '--no-heading', '-S', '--max-count', '6', '-g', '!node_modules/**', '-g', '!.git/**', pattern, '.'], {
|
|
374
|
+
cwd: rootDir,
|
|
375
|
+
windowsHide: true,
|
|
376
|
+
})
|
|
377
|
+
let out = ''
|
|
378
|
+
let settled = false
|
|
379
|
+
const timer = setTimeout(() => {
|
|
380
|
+
if (settled) return
|
|
381
|
+
settled = true
|
|
382
|
+
try { child.kill('SIGTERM') } catch {}
|
|
383
|
+
resolve(null)
|
|
384
|
+
}, 5_000)
|
|
385
|
+
|
|
386
|
+
child.stdout?.on('data', d => {
|
|
387
|
+
if (out.length < 24_000) out += String(d)
|
|
388
|
+
})
|
|
389
|
+
child.on('error', () => {
|
|
390
|
+
if (settled) return
|
|
391
|
+
settled = true
|
|
392
|
+
clearTimeout(timer)
|
|
393
|
+
resolve(null)
|
|
394
|
+
})
|
|
395
|
+
child.on('close', (code) => {
|
|
396
|
+
if (settled) return
|
|
397
|
+
settled = true
|
|
398
|
+
clearTimeout(timer)
|
|
399
|
+
if (code === 0 || code === 1) {
|
|
400
|
+
const lines = out.split(/\r?\n/).filter(Boolean).slice(0, maxHits)
|
|
401
|
+
resolve(lines)
|
|
402
|
+
} else {
|
|
403
|
+
resolve(null)
|
|
404
|
+
}
|
|
405
|
+
})
|
|
406
|
+
})
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** 执行单个参谋长工具调用,实施四档权限与禁止红线护栏。 */
|
|
410
|
+
export async function executeChiefToolCall(deps, call, execCtx = {}) {
|
|
411
|
+
const tool = String(call && (call.tool || call.name) || '').trim()
|
|
412
|
+
const args = (call && call.args && typeof call.args === 'object') ? call.args : (call && typeof call === 'object' ? call : {})
|
|
413
|
+
const permissionMode = normalizePermissionMode(execCtx.permissionMode)
|
|
414
|
+
const cwd = String(execCtx.cwd || process.cwd())
|
|
415
|
+
const rootId = String(execCtx.rootId || '')
|
|
416
|
+
const board = execCtx.board || {}
|
|
417
|
+
const readOnlyToolsOnly = Boolean(execCtx.readOnlyToolsOnly)
|
|
418
|
+
|
|
419
|
+
const deny = (error, badge) => ({
|
|
420
|
+
tool,
|
|
421
|
+
ok: false,
|
|
422
|
+
denied: true,
|
|
423
|
+
error,
|
|
424
|
+
badge: badge || `⛔ 拒绝 ${tool}`,
|
|
425
|
+
})
|
|
426
|
+
|
|
427
|
+
if (!tool) return deny('缺少工具名 tool')
|
|
428
|
+
if (readOnlyToolsOnly && !['read_file', 'list_dir', 'search_files'].includes(tool)) {
|
|
429
|
+
return deny(`后台复盘轮次仅允许只读核验工具(${tool} 已跳过)`)
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
switch (tool) {
|
|
433
|
+
case 'read_file': {
|
|
434
|
+
const targetRel = String(args.path || '').trim()
|
|
435
|
+
if (!targetRel) return deny('read_file 需要 path 参数')
|
|
436
|
+
const abs = path.resolve(cwd, targetRel)
|
|
437
|
+
if (isSensitiveCredentialPath(abs)) {
|
|
438
|
+
return deny(`安全护栏拒绝读取凭据文件:${path.basename(abs)}`, `🛡️ 拦截读取凭据`)
|
|
439
|
+
}
|
|
440
|
+
if (!fs.existsSync(abs)) return { tool, ok: false, error: `文件不存在:${abs}`, badge: `⚠️ 未找到 ${path.basename(abs)}` }
|
|
441
|
+
try {
|
|
442
|
+
const raw = fs.readFileSync(abs, 'utf8')
|
|
443
|
+
const lines = raw.split(/\r?\n/)
|
|
444
|
+
const startLine = Math.max(1, Math.round(Number(args.startLine) || 1))
|
|
445
|
+
const endLine = Math.min(lines.length, Math.max(startLine, Math.round(Number(args.endLine) || (startLine + 179))))
|
|
446
|
+
const numbered = lines.slice(startLine - 1, endLine).map((l, idx) => `${startLine + idx}: ${l}`).join('\n')
|
|
447
|
+
return {
|
|
448
|
+
tool,
|
|
449
|
+
ok: true,
|
|
450
|
+
path: abs,
|
|
451
|
+
totalLines: lines.length,
|
|
452
|
+
range: `${startLine}-${endLine}`,
|
|
453
|
+
content: truncateMiddle(numbered, 14_000),
|
|
454
|
+
badge: `📖 读取 ${path.basename(abs)}`,
|
|
455
|
+
}
|
|
456
|
+
} catch (err) {
|
|
457
|
+
return { tool, ok: false, error: String(err && err.message ? err.message : err), badge: `⚠️ 读取失败` }
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
case 'list_dir': {
|
|
462
|
+
const targetRel = String(args.path || '.').trim() || '.'
|
|
463
|
+
const abs = path.resolve(cwd, targetRel)
|
|
464
|
+
if (!fs.existsSync(abs)) return { tool, ok: false, error: `目录不存在:${abs}`, badge: `⚠️ 目录不存在` }
|
|
465
|
+
try {
|
|
466
|
+
const items = fs.readdirSync(abs, { withFileTypes: true }).slice(0, 120).map(ent => {
|
|
467
|
+
let size = 0
|
|
468
|
+
if (ent.isFile()) {
|
|
469
|
+
try { size = fs.statSync(path.join(abs, ent.name)).size } catch {}
|
|
470
|
+
}
|
|
471
|
+
return { name: ent.name, type: ent.isDirectory() ? 'dir' : 'file', ...(ent.isFile() ? { size } : {}) }
|
|
472
|
+
})
|
|
473
|
+
return { tool, ok: true, path: abs, items, badge: `📂 列目录 ${path.basename(abs) || abs}` }
|
|
474
|
+
} catch (err) {
|
|
475
|
+
return { tool, ok: false, error: String(err && err.message ? err.message : err), badge: `⚠️ 列目录失败` }
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
case 'search_files': {
|
|
480
|
+
const pattern = String(args.pattern || args.query || '').trim()
|
|
481
|
+
if (!pattern) return deny('search_files 需要 pattern 参数')
|
|
482
|
+
const searchRoot = path.resolve(cwd, String(args.path || '.').trim() || '.')
|
|
483
|
+
if (!fs.existsSync(searchRoot)) return { tool, ok: false, error: `搜索目录不存在:${searchRoot}`, badge: `⚠️ 搜索目录不存在` }
|
|
484
|
+
const maxHits = Math.min(50, Math.max(1, Math.round(Number(args.maxHits) || 30)))
|
|
485
|
+
let hits = await runRgSearch(searchRoot, pattern, maxHits)
|
|
486
|
+
if (hits === null) hits = searchFilesFallbackNode(searchRoot, pattern, maxHits)
|
|
487
|
+
return { tool, ok: true, path: searchRoot, pattern, hits, count: hits.length, badge: `🔎 搜索 "${clamp(pattern, 18)}"` }
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
case 'write_file': {
|
|
491
|
+
const targetRel = String(args.path || '').trim()
|
|
492
|
+
if (!targetRel) return deny('write_file 需要 path 参数')
|
|
493
|
+
const abs = path.resolve(cwd, targetRel)
|
|
494
|
+
if (permissionMode === 'read-only') {
|
|
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
|
+
}
|
|
510
|
+
try {
|
|
511
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true })
|
|
512
|
+
fs.writeFileSync(abs, String(args.content ?? ''), 'utf8')
|
|
513
|
+
return { tool, ok: true, path: abs, bytes: Buffer.byteLength(String(args.content ?? ''), 'utf8'), badge: `✍️ 写入 ${path.basename(abs)}` }
|
|
514
|
+
} catch (err) {
|
|
515
|
+
return { tool, ok: false, error: String(err && err.message ? err.message : err), badge: `⚠️ 写入失败` }
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
case 'edit_file': {
|
|
520
|
+
const targetRel = String(args.path || '').trim()
|
|
521
|
+
const targetStr = String(args.target ?? '')
|
|
522
|
+
const replaceStr = String(args.replacement ?? '')
|
|
523
|
+
if (!targetRel || !targetStr) return deny('edit_file 需要 path 与 target 参数')
|
|
524
|
+
const abs = path.resolve(cwd, targetRel)
|
|
525
|
+
if (permissionMode === 'read-only') {
|
|
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)}` }
|
|
542
|
+
try {
|
|
543
|
+
const prev = fs.readFileSync(abs, 'utf8')
|
|
544
|
+
const idx = prev.indexOf(targetStr)
|
|
545
|
+
if (idx < 0) return { tool, ok: false, error: `未在 ${path.basename(abs)} 中匹配到 target 文本`, badge: `⚠️ 替换未命中` }
|
|
546
|
+
const next = prev.slice(0, idx) + replaceStr + prev.slice(idx + targetStr.length)
|
|
547
|
+
fs.writeFileSync(abs, next, 'utf8')
|
|
548
|
+
return { tool, ok: true, path: abs, badge: `✏️ 修改 ${path.basename(abs)}` }
|
|
549
|
+
} catch (err) {
|
|
550
|
+
return { tool, ok: false, error: String(err && err.message ? err.message : err), badge: `⚠️ 编辑失败` }
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
case 'run_command': {
|
|
555
|
+
const command = String(args.command || args.cmd || '').trim()
|
|
556
|
+
if (!command) return deny('run_command 需要 command 参数')
|
|
557
|
+
const runCwd = path.resolve(cwd, String(args.cwd || '.').trim() || '.')
|
|
558
|
+
const boundCheck = checkForbiddenBounds(board, 'run_command', command)
|
|
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: `⚠️ 目录不存在` }
|
|
572
|
+
const execOut = await runSubprocess(command, runCwd, args.timeoutMs)
|
|
573
|
+
return {
|
|
574
|
+
tool,
|
|
575
|
+
ok: execOut.ok,
|
|
576
|
+
exitCode: execOut.exitCode,
|
|
577
|
+
timedOut: execOut.timedOut,
|
|
578
|
+
cwd: runCwd,
|
|
579
|
+
stdout: execOut.stdout,
|
|
580
|
+
stderr: execOut.stderr,
|
|
581
|
+
badge: `⚡ 执行 (${execOut.timedOut ? '超时' : 'exit ' + execOut.exitCode})`,
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
case 'subagent_dispatch': {
|
|
586
|
+
if (permissionMode === 'read-only') {
|
|
587
|
+
return deny('当前权限为「👁 仅可查看」,无法派发子代理任务。', '🔒 只读禁派')
|
|
588
|
+
}
|
|
589
|
+
const prompt = String(args.prompt || args.message || args.text || '').trim()
|
|
590
|
+
if (!prompt) return deny('subagent_dispatch 需要 prompt 指令')
|
|
591
|
+
let taskId = String(args.taskId || args.id || '').trim()
|
|
592
|
+
if (!taskId && typeof deps.runAction === 'function') {
|
|
593
|
+
const addRes = deps.runAction({
|
|
594
|
+
action: 'task.add',
|
|
595
|
+
title: clamp(args.title || prompt, 60),
|
|
596
|
+
owner: String(args.agent || args.subagent || '').trim(),
|
|
597
|
+
session: rootId,
|
|
598
|
+
by: 'chief',
|
|
599
|
+
})
|
|
600
|
+
if (addRes && addRes.ok && addRes.task && addRes.task.id) {
|
|
601
|
+
taskId = String(addRes.task.id)
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
if (typeof deps.executeSubagentAction !== 'function') {
|
|
605
|
+
return { tool, ok: false, error: '当前宿主未挂载子代理调度接口', badge: '⚠️ 无子代理引擎' }
|
|
606
|
+
}
|
|
607
|
+
const dRes = await deps.executeSubagentAction({
|
|
608
|
+
action: 'task.dispatch',
|
|
609
|
+
id: taskId,
|
|
610
|
+
agent: args.agent || args.subagent || '',
|
|
611
|
+
prompt,
|
|
612
|
+
preset: args.preset || '',
|
|
613
|
+
force: Boolean(args.force),
|
|
614
|
+
session: rootId,
|
|
615
|
+
by: 'chief',
|
|
616
|
+
})
|
|
617
|
+
return {
|
|
618
|
+
tool,
|
|
619
|
+
ok: Boolean(dRes && dRes.ok),
|
|
620
|
+
...(dRes || {}),
|
|
621
|
+
badge: dRes && dRes.ok ? `🚀 派发 @${dRes.dispatched?.agent || args.agent || 'worker'}` : '⚠️ 派发失败',
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
case 'subagent_steer': {
|
|
626
|
+
if (permissionMode === 'read-only') return deny('当前权限为「👁 仅可查看」,无法向子代理发指令。')
|
|
627
|
+
if (typeof deps.executeSubagentAction !== 'function') return { tool, ok: false, error: '当前宿主未挂载子代理接口' }
|
|
628
|
+
const sRes = await deps.executeSubagentAction({
|
|
629
|
+
action: 'team.steer',
|
|
630
|
+
agent: args.agent || args.target || '',
|
|
631
|
+
id: args.taskId || args.id || '',
|
|
632
|
+
message: args.message || args.prompt || args.text || '',
|
|
633
|
+
session: rootId,
|
|
634
|
+
by: 'chief',
|
|
635
|
+
})
|
|
636
|
+
return { tool, ok: Boolean(sRes && sRes.ok), ...(sRes || {}), badge: sRes && sRes.ok ? `💬 引导 @${args.agent || 'worker'}` : '⚠️ 引导失败' }
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
case 'subagent_interrupt': {
|
|
640
|
+
if (permissionMode === 'read-only') return deny('当前权限为「👁 仅可查看」,无法中断子代理。')
|
|
641
|
+
if (typeof deps.executeSubagentAction !== 'function') return { tool, ok: false, error: '当前宿主未挂载子代理接口' }
|
|
642
|
+
const iRes = await deps.executeSubagentAction({
|
|
643
|
+
action: 'team.interrupt',
|
|
644
|
+
agent: args.agent || args.target || '',
|
|
645
|
+
id: args.taskId || args.id || '',
|
|
646
|
+
session: rootId,
|
|
647
|
+
by: 'chief',
|
|
648
|
+
})
|
|
649
|
+
return { tool, ok: Boolean(iRes && iRes.ok), ...(iRes || {}), badge: iRes && iRes.ok ? `⏹ 中断 @${args.agent || 'worker'}` : '⚠️ 中断失败' }
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
case 'archive_write': {
|
|
653
|
+
if (permissionMode === 'read-only') return deny('当前权限为「👁 仅可查看」,不能写入档案柜。')
|
|
654
|
+
if (typeof execCtx.upsertArchiveFn !== 'function') {
|
|
655
|
+
return { tool, ok: false, error: '档案写入服务未就绪', badge: '⚠️ 无档案写口' }
|
|
656
|
+
}
|
|
657
|
+
const scope = args.vaultScope === 'global' ? 'global' : 'session'
|
|
658
|
+
const out = await execCtx.upsertArchiveFn({
|
|
659
|
+
vaultScope: scope,
|
|
660
|
+
folder: args.folder || 'inbox',
|
|
661
|
+
title: clamp(args.title || '参谋长工作归档', 72),
|
|
662
|
+
summary: clamp(args.summary || '', 160),
|
|
663
|
+
body: String(args.body || args.text || ''),
|
|
664
|
+
tags: Array.isArray(args.tags) ? args.tags : [],
|
|
665
|
+
})
|
|
666
|
+
return {
|
|
667
|
+
tool,
|
|
668
|
+
ok: Boolean(out && out.ok),
|
|
669
|
+
...(out || {}),
|
|
670
|
+
badge: out && out.ok ? `🗄️ 归档(${scope === 'global' ? '全局' : '本会话'})` : '⚠️ 归档失败',
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
case 'session_compact': {
|
|
675
|
+
if (permissionMode === 'read-only') return deny('当前权限为「👁 仅可查看」,不能触发上下文压缩。')
|
|
676
|
+
if (typeof execCtx.compactNowFn !== 'function') {
|
|
677
|
+
return { tool, ok: false, error: '压缩服务未就绪', badge: '⚠️ 无压缩引擎' }
|
|
678
|
+
}
|
|
679
|
+
try {
|
|
680
|
+
const cRes = await execCtx.compactNowFn(String(args.reason || '参谋长主动执行抢救与上下文压缩'))
|
|
681
|
+
if (cRes && cRes.ok) {
|
|
682
|
+
return {
|
|
683
|
+
tool,
|
|
684
|
+
ok: true,
|
|
685
|
+
...cRes,
|
|
686
|
+
badge: cRes.noop ? '🗄️ 已归档(免压)' : '🗜 完成抢救压缩',
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return {
|
|
690
|
+
tool,
|
|
691
|
+
ok: false,
|
|
692
|
+
...(cRes && typeof cRes === 'object' ? cRes : { error: String(cRes || '压缩未完成') }),
|
|
693
|
+
error: (cRes && cRes.error) || '压缩未完成',
|
|
694
|
+
badge: '⚠️ 压缩未完成',
|
|
695
|
+
}
|
|
696
|
+
} catch (e) {
|
|
697
|
+
return {
|
|
698
|
+
tool,
|
|
699
|
+
ok: false,
|
|
700
|
+
error: (e && e.message) || String(e || '压缩执行异常'),
|
|
701
|
+
badge: '⚠️ 压缩异常',
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
default:
|
|
707
|
+
return deny(`未知参谋长工具:${tool}`, `⚠️ 未知工具 ${tool}`)
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/**
|
|
712
|
+
* 参谋长多步实权 Agentic 循环:支持最多 `maxSteps` 轮工具自驱执行后综合汇报。
|
|
713
|
+
*/
|
|
714
|
+
export async function runChiefAgenticLoop(deps, {
|
|
715
|
+
rootId = '',
|
|
716
|
+
sessionId = '',
|
|
717
|
+
system = '',
|
|
718
|
+
initialPrompt = '',
|
|
719
|
+
imageBlocks = [],
|
|
720
|
+
allowTextFallbackOnVisionMiss = false,
|
|
721
|
+
permissionMode = DEFAULT_CHIEF_PERMISSION_MODE,
|
|
722
|
+
board = null,
|
|
723
|
+
maxSteps = 4,
|
|
724
|
+
readOnlyToolsOnly = false,
|
|
725
|
+
disableTools = false,
|
|
726
|
+
callLlmFn,
|
|
727
|
+
extractJsonFn,
|
|
728
|
+
upsertArchiveFn,
|
|
729
|
+
compactNowFn,
|
|
730
|
+
} = {}) {
|
|
731
|
+
const perm = normalizePermissionMode(permissionMode)
|
|
732
|
+
const cwd = (typeof deps?.getSessionCwd === 'function' ? deps.getSessionCwd(rootId || sessionId) : '') || process.cwd()
|
|
733
|
+
const toolBadges = []
|
|
734
|
+
const toolRecords = []
|
|
735
|
+
let prompt = String(initialPrompt || '')
|
|
736
|
+
let lastLlmRes = null
|
|
737
|
+
let parsed = null
|
|
738
|
+
|
|
739
|
+
const cleanRes = (res) => {
|
|
740
|
+
if (!res || typeof res !== 'object') return res
|
|
741
|
+
const raw = typeof res.text === 'string' ? res.text : ''
|
|
742
|
+
const cleaned = stripToolCallMarkup(raw)
|
|
743
|
+
return { ...res, text: cleaned }
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
if (disableTools) {
|
|
747
|
+
lastLlmRes = await callLlmFn({
|
|
748
|
+
prompt,
|
|
749
|
+
system,
|
|
750
|
+
imageBlocks,
|
|
751
|
+
allowTextFallbackOnVisionMiss,
|
|
752
|
+
})
|
|
753
|
+
if (!lastLlmRes || !lastLlmRes.ok) {
|
|
754
|
+
return { ok: false, llmRes: lastLlmRes, parsed: null, toolBadges, toolRecords }
|
|
755
|
+
}
|
|
756
|
+
const cleanedRes = cleanRes(lastLlmRes)
|
|
757
|
+
parsed = typeof extractJsonFn === 'function' ? extractJsonFn(cleanedRes.text) : null
|
|
758
|
+
if (parsed && typeof parsed.reply === 'string') {
|
|
759
|
+
parsed.reply = stripToolCallMarkup(parsed.reply)
|
|
760
|
+
}
|
|
761
|
+
return { ok: true, llmRes: cleanedRes, parsed, toolBadges, toolRecords }
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
const permHeader = `\n\n[当前参谋长权限级别] permissionMode="${perm}"${perm === 'danger-full-access' ? '(最高完全权限:允许直接读写文件、执行命令、调度子代理、治理看板与归档压缩)' : perm === 'workspace-write' ? `(工作区内修改:仅限 ${cwd} 内写入与跑命令)` : perm === 'read-only' ? '(仅可查看:只读检查,拒绝一切写入和变更操作)' : '(自动审查 EXP:可只读查证,变更需转建议或切完全权限)'}`
|
|
765
|
+
const stepsLimit = Math.max(1, maxSteps)
|
|
766
|
+
let ranToolsOnLastStep = false
|
|
767
|
+
|
|
768
|
+
for (let step = 0; step < stepsLimit; step += 1) {
|
|
769
|
+
ranToolsOnLastStep = false
|
|
770
|
+
lastLlmRes = await callLlmFn({
|
|
771
|
+
prompt: step === 0 ? (prompt + permHeader) : prompt,
|
|
772
|
+
system,
|
|
773
|
+
imageBlocks: step === 0 ? imageBlocks : [],
|
|
774
|
+
allowTextFallbackOnVisionMiss,
|
|
775
|
+
})
|
|
776
|
+
if (!lastLlmRes || !lastLlmRes.ok) {
|
|
777
|
+
return { ok: false, llmRes: lastLlmRes, parsed: null, toolBadges, toolRecords }
|
|
778
|
+
}
|
|
779
|
+
parsed = typeof extractJsonFn === 'function' ? extractJsonFn(lastLlmRes.text) : null
|
|
780
|
+
const jsonCalls = parsed && Array.isArray(parsed.toolCalls) ? parsed.toolCalls.filter(c => c && (c.tool || c.name)).slice(0, 4) : []
|
|
781
|
+
const dsmlCalls = !jsonCalls.length ? parseDsmlToolCalls(lastLlmRes.text) : []
|
|
782
|
+
const calls = jsonCalls.length ? jsonCalls : dsmlCalls
|
|
783
|
+
if (!calls.length) {
|
|
784
|
+
const cleanedRes = parsed ? lastLlmRes : cleanRes(lastLlmRes)
|
|
785
|
+
if (!parsed && typeof extractJsonFn === 'function') {
|
|
786
|
+
parsed = extractJsonFn(cleanedRes.text)
|
|
787
|
+
}
|
|
788
|
+
if (parsed && typeof parsed.reply === 'string') {
|
|
789
|
+
parsed.reply = stripToolCallMarkup(parsed.reply)
|
|
790
|
+
}
|
|
791
|
+
return { ok: true, llmRes: cleanedRes, parsed, toolBadges, toolRecords }
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// 执行本轮工具调用
|
|
795
|
+
ranToolsOnLastStep = true
|
|
796
|
+
const stepOutputs = []
|
|
797
|
+
for (const c of calls) {
|
|
798
|
+
const execRes = await executeChiefToolCall(deps, c, {
|
|
799
|
+
rootId,
|
|
800
|
+
sessionId: sessionId || rootId,
|
|
801
|
+
cwd,
|
|
802
|
+
permissionMode: perm,
|
|
803
|
+
board,
|
|
804
|
+
readOnlyToolsOnly,
|
|
805
|
+
upsertArchiveFn,
|
|
806
|
+
compactNowFn,
|
|
807
|
+
})
|
|
808
|
+
toolRecords.push({ step: step + 1, call: c, result: execRes })
|
|
809
|
+
if (execRes.badge && !toolBadges.includes(execRes.badge)) {
|
|
810
|
+
toolBadges.push(execRes.badge)
|
|
811
|
+
}
|
|
812
|
+
stepOutputs.push({
|
|
813
|
+
tool: execRes.tool,
|
|
814
|
+
args: c.args || {},
|
|
815
|
+
result: execRes,
|
|
816
|
+
})
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
const obsBlock = stepOutputs.map((item, i) => [
|
|
820
|
+
`### 工具 #${i + 1} \`${item.tool}\` 执行回执`,
|
|
821
|
+
JSON.stringify(item.result, null, 2),
|
|
822
|
+
].join('\n')).join('\n\n')
|
|
823
|
+
|
|
824
|
+
const isFinalStepSoon = step + 2 >= stepsLimit
|
|
825
|
+
prompt = [
|
|
826
|
+
prompt,
|
|
827
|
+
'',
|
|
828
|
+
`## 第 ${step + 1} 步实权工具真实执行结果`,
|
|
829
|
+
obsBlock,
|
|
830
|
+
'',
|
|
831
|
+
isFinalStepSoon
|
|
832
|
+
? '你已接近本轮工具调用步数上限,请立即基于上述真实回执输出最终结论 JSON(务必不要再带 `"toolCalls"` 或任何 DSML/XML 标签)。'
|
|
833
|
+
: '请根据上述真实回执决定:若仍需进一步查看/修改/验证则继续附带下一批 `"toolCalls"`;否则直接输出最终结论 JSON(不再包含 `"toolCalls"` 或 DSML 标签)。',
|
|
834
|
+
].join('\n')
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// Reached maxSteps while still invoking tools: perform one tool-free synthesis call so raw tool markup NEVER exits the loop
|
|
838
|
+
if (ranToolsOnLastStep) {
|
|
839
|
+
try {
|
|
840
|
+
const synthRes = await callLlmFn({
|
|
841
|
+
prompt: prompt + '\n\n【重要停手收口】工具调用步数已用尽!现在严禁再输出任何 `toolCalls`、`<|DSML|calls>` 或 `<invoke>` 标签,请直接根据上面已拿到的真实信息与对话快照,用中文给出最终 `{ "reply": "…" }`!',
|
|
842
|
+
system,
|
|
843
|
+
imageBlocks: [],
|
|
844
|
+
allowTextFallbackOnVisionMiss,
|
|
845
|
+
})
|
|
846
|
+
if (synthRes && synthRes.ok) {
|
|
847
|
+
lastLlmRes = cleanRes(synthRes)
|
|
848
|
+
parsed = typeof extractJsonFn === 'function' ? extractJsonFn(lastLlmRes.text) : null
|
|
849
|
+
}
|
|
850
|
+
} catch {}
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
const finalRes = cleanRes(lastLlmRes)
|
|
854
|
+
if (!parsed && finalRes && finalRes.ok && typeof extractJsonFn === 'function') {
|
|
855
|
+
parsed = extractJsonFn(finalRes.text)
|
|
856
|
+
}
|
|
857
|
+
if (parsed && typeof parsed.reply === 'string') {
|
|
858
|
+
parsed.reply = stripToolCallMarkup(parsed.reply)
|
|
859
|
+
}
|
|
860
|
+
return { ok: Boolean(finalRes && finalRes.ok), llmRes: finalRes, parsed, toolBadges, toolRecords }
|
|
861
|
+
}
|