@zhin.js/agent 0.0.17 → 0.0.19

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.
Files changed (61) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +14 -8
  3. package/lib/builtin-tools.d.ts +5 -137
  4. package/lib/builtin-tools.d.ts.map +1 -1
  5. package/lib/builtin-tools.js +321 -732
  6. package/lib/builtin-tools.js.map +1 -1
  7. package/lib/discover-agents.d.ts +28 -0
  8. package/lib/discover-agents.d.ts.map +1 -0
  9. package/lib/discover-agents.js +116 -0
  10. package/lib/discover-agents.js.map +1 -0
  11. package/lib/discover-skills.d.ts +49 -0
  12. package/lib/discover-skills.d.ts.map +1 -0
  13. package/lib/discover-skills.js +297 -0
  14. package/lib/discover-skills.js.map +1 -0
  15. package/lib/discover-tools.d.ts +56 -0
  16. package/lib/discover-tools.d.ts.map +1 -0
  17. package/lib/discover-tools.js +263 -0
  18. package/lib/discover-tools.js.map +1 -0
  19. package/lib/discovery-utils.d.ts +27 -0
  20. package/lib/discovery-utils.d.ts.map +1 -0
  21. package/lib/discovery-utils.js +96 -0
  22. package/lib/discovery-utils.js.map +1 -0
  23. package/lib/file-policy.d.ts +41 -4
  24. package/lib/file-policy.d.ts.map +1 -1
  25. package/lib/file-policy.js +126 -4
  26. package/lib/file-policy.js.map +1 -1
  27. package/lib/index.d.ts +1 -1
  28. package/lib/index.d.ts.map +1 -1
  29. package/lib/index.js +1 -1
  30. package/lib/index.js.map +1 -1
  31. package/lib/init/create-zhin-agent.d.ts.map +1 -1
  32. package/lib/init/create-zhin-agent.js +3 -1
  33. package/lib/init/create-zhin-agent.js.map +1 -1
  34. package/lib/init/register-builtin-tools.d.ts.map +1 -1
  35. package/lib/init/register-builtin-tools.js +51 -54
  36. package/lib/init/register-builtin-tools.js.map +1 -1
  37. package/lib/zhin-agent/config.js +1 -1
  38. package/lib/zhin-agent/config.js.map +1 -1
  39. package/lib/zhin-agent/exec-policy.d.ts +48 -2
  40. package/lib/zhin-agent/exec-policy.d.ts.map +1 -1
  41. package/lib/zhin-agent/exec-policy.js +184 -23
  42. package/lib/zhin-agent/exec-policy.js.map +1 -1
  43. package/lib/zhin-agent/prompt.d.ts +14 -0
  44. package/lib/zhin-agent/prompt.d.ts.map +1 -1
  45. package/lib/zhin-agent/prompt.js +192 -45
  46. package/lib/zhin-agent/prompt.js.map +1 -1
  47. package/package.json +3 -3
  48. package/src/builtin-tools.ts +333 -835
  49. package/src/discover-agents.ts +138 -0
  50. package/src/discover-skills.ts +325 -0
  51. package/src/discover-tools.ts +302 -0
  52. package/src/discovery-utils.ts +96 -0
  53. package/src/file-policy.ts +152 -4
  54. package/src/index.ts +5 -1
  55. package/src/init/create-zhin-agent.ts +3 -1
  56. package/src/init/register-builtin-tools.ts +51 -62
  57. package/src/zhin-agent/config.ts +1 -1
  58. package/src/zhin-agent/exec-policy.ts +229 -24
  59. package/src/zhin-agent/prompt.ts +209 -47
  60. package/tests/exec-policy.test.ts +355 -0
  61. package/tests/file-policy.test.ts +189 -1
@@ -5,17 +5,12 @@
5
5
  import * as fs from 'fs';
6
6
  import * as os from 'os';
7
7
  import * as path from 'path';
8
- import { getPlugin, type Tool, type SkillFeature, type AgentPreset } from '@zhin.js/core';
9
- import {
10
- collectPluginSkillSearchRoots,
11
- createBuiltinTools,
12
- discoverWorkspaceSkills,
13
- discoverWorkspaceAgents,
14
- discoverWorkspaceTools,
15
- buildToolFromMeta,
16
- loadAlwaysSkillsContent,
17
- buildSkillsSummaryXML,
18
- } from '../builtin-tools.js';
8
+ import { getPlugin, type Tool, type SkillFeature, type AgentPresetFeature } from '@zhin.js/core';
9
+ import { createBuiltinTools } from '../builtin-tools.js';
10
+ import { collectPluginSkillSearchRoots } from '../discovery-utils.js';
11
+ import { discoverWorkspaceSkills, loadAlwaysSkillsContent, buildSkillsSummaryXML } from '../discover-skills.js';
12
+ import { discoverWorkspaceAgents } from '../discover-agents.js';
13
+ import { discoverWorkspaceTools, buildToolFromMeta } from '../discover-tools.js';
19
14
  import { resolveSkillInstructionMaxChars, DEFAULT_CONFIG } from '../zhin-agent/config.js';
20
15
  import { loadBootstrapFiles, buildContextFiles, buildBootstrapContextSection } from '../bootstrap.js';
21
16
  import { triggerAIHook, createAIHookEvent } from '../hooks.js';
@@ -34,6 +29,7 @@ export function registerBuiltinTools(refs: AIServiceRefs): void {
34
29
  const fullCfg = { ...DEFAULT_CONFIG, ...agentCfg } as Required<import('../zhin-agent/config.js').ZhinAgentConfig>;
35
30
  const modelName = provider.models[0] || '';
36
31
  const builtinTools = createBuiltinTools({
32
+ plugin,
37
33
  skillInstructionMaxChars: resolveSkillInstructionMaxChars(fullCfg, modelName),
38
34
  pluginSkillRootsResolver: () => collectPluginSkillSearchRoots(root),
39
35
  skillFileLookup: (name: string) => {
@@ -57,31 +53,39 @@ export function registerBuiltinTools(refs: AIServiceRefs): void {
57
53
  const existing = skillFeature.getByPlugin(root.name);
58
54
  for (const s of existing) skillFeature.remove(s);
59
55
  const skills = await discoverWorkspaceSkills(root);
60
- if (skills.length === 0) return 0;
61
- const allRegisteredTools = toolService.getAll();
62
- const toolNameIndex = new Map<string, Tool>();
63
- for (const t of allRegisteredTools) {
64
- toolNameIndex.set(t.name, t);
65
- const parts = t.name.split('_');
66
- if (parts.length === 2) toolNameIndex.set(`${parts[1]}_${parts[0]}`, t);
67
- }
68
- for (const s of skills) {
69
- const associatedTools: Tool[] = [];
70
- const toolNames = s.toolNames || [];
71
- for (const toolName of toolNames) {
72
- let tool = toolService.get(toolName) || toolNameIndex.get(toolName);
73
- if (tool) associatedTools.push(tool);
56
+ if (skills.length > 0) {
57
+ const allRegisteredTools = toolService.getAll();
58
+ const toolNameIndex = new Map<string, Tool>();
59
+ for (const t of allRegisteredTools) {
60
+ toolNameIndex.set(t.name, t);
61
+ const parts = t.name.split('_');
62
+ if (parts.length === 2) toolNameIndex.set(`${parts[1]}_${parts[0]}`, t);
74
63
  }
75
- skillFeature.add({
76
- name: s.name,
77
- description: s.description,
78
- tools: associatedTools,
79
- keywords: s.keywords || [],
80
- tags: s.tags || [],
81
- pluginName: root.name,
82
- filePath: s.filePath,
83
- always: s.always,
84
- }, root.name);
64
+ for (const s of skills) {
65
+ const associatedTools: Tool[] = [];
66
+ const toolNames = s.toolNames || [];
67
+ for (const toolName of toolNames) {
68
+ let tool = toolService.get(toolName) || toolNameIndex.get(toolName);
69
+ if (tool) associatedTools.push(tool);
70
+ }
71
+ skillFeature.add({
72
+ name: s.name,
73
+ description: s.description,
74
+ tools: associatedTools,
75
+ keywords: s.keywords || [],
76
+ tags: s.tags || [],
77
+ pluginName: root.name,
78
+ filePath: s.filePath,
79
+ always: s.always,
80
+ }, root.name);
81
+ }
82
+ }
83
+ // Inject always-on skills content + XML summary into agent
84
+ if (refs.zhinAgent) {
85
+ const alwaysContent = await loadAlwaysSkillsContent(skills);
86
+ const skillsXml = buildSkillsSummaryXML(skills);
87
+ refs.zhinAgent.setActiveSkillsContext(alwaysContent);
88
+ refs.zhinAgent.setSkillsSummaryXML(skillsXml);
85
89
  }
86
90
  return skills.length;
87
91
  }
@@ -116,15 +120,20 @@ export function registerBuiltinTools(refs: AIServiceRefs): void {
116
120
  return added;
117
121
  }
118
122
 
119
- // 已发现的 Agent 预设(本地缓存,无需存储到 Plugin 树)
120
- const discoveredAgents = new Map<string, AgentPreset>();
121
-
122
123
  /**
123
- * Discover *.agent.md files and register agent presets.
124
+ * Discover *.agent.md files and register agent presets into AgentPresetFeature.
124
125
  */
125
126
  async function syncWorkspaceAgents(): Promise<number> {
127
+ const agentPresetFeature = root.inject?.('agentPreset') as AgentPresetFeature | undefined;
128
+ if (!agentPresetFeature) return 0;
129
+
130
+ // Remove previously discovered presets for this plugin
131
+ const existing = agentPresetFeature.getByPlugin(root.name);
132
+ for (const p of existing) agentPresetFeature.remove(p);
133
+
126
134
  const agentMetas = await discoverWorkspaceAgents(root);
127
135
  if (agentMetas.length === 0) return 0;
136
+
128
137
  const allRegisteredTools = toolService.getAll();
129
138
  const toolNameIndex = new Map<string, import('@zhin.js/core').Tool>();
130
139
  for (const t of allRegisteredTools) {
@@ -132,7 +141,7 @@ export function registerBuiltinTools(refs: AIServiceRefs): void {
132
141
  }
133
142
  let added = 0;
134
143
  for (const meta of agentMetas) {
135
- if (discoveredAgents.has(meta.name)) continue;
144
+ if (agentPresetFeature.get(meta.name)) continue;
136
145
  const associatedTools: import('@zhin.js/core').Tool[] = [];
137
146
  for (const toolName of meta.toolNames || []) {
138
147
  const tool = toolService.get(toolName) || toolNameIndex.get(toolName);
@@ -145,7 +154,7 @@ export function registerBuiltinTools(refs: AIServiceRefs): void {
145
154
  const body = content.replace(/^---\s*\n[\s\S]*?\n---\s*(?:\n|$)/, '').trim();
146
155
  if (body) systemPrompt = body;
147
156
  } catch { /* ignore */ }
148
- discoveredAgents.set(meta.name, {
157
+ agentPresetFeature.add({
149
158
  name: meta.name,
150
159
  description: meta.description,
151
160
  keywords: meta.keywords,
@@ -156,7 +165,7 @@ export function registerBuiltinTools(refs: AIServiceRefs): void {
156
165
  provider: meta.provider,
157
166
  maxIterations: meta.maxIterations,
158
167
  filePath: meta.filePath,
159
- });
168
+ }, root.name);
160
169
  added++;
161
170
  }
162
171
  return added;
@@ -224,19 +233,6 @@ export function registerBuiltinTools(refs: AIServiceRefs): void {
224
233
  logger.debug(`Bootstrap files not loaded: ${e.message}`);
225
234
  }
226
235
 
227
- // Step 3: inject always-on skills content + XML summary
228
- try {
229
- const skillsForContext = await discoverWorkspaceSkills(root);
230
- const alwaysContent = await loadAlwaysSkillsContent(skillsForContext);
231
- const skillsXml = buildSkillsSummaryXML(skillsForContext);
232
- if (refs.zhinAgent) {
233
- refs.zhinAgent.setActiveSkillsContext(alwaysContent);
234
- refs.zhinAgent.setSkillsSummaryXML(skillsXml);
235
- }
236
- } catch (e: unknown) {
237
- logger.debug(`Skills context not set: ${e instanceof Error ? e.message : String(e)}`);
238
- }
239
-
240
236
  // Trigger agent:bootstrap hook
241
237
  const skillFeature2 = root.inject('skill') as SkillFeature | undefined;
242
238
  await triggerAIHook(createAIHookEvent('agent', 'bootstrap', undefined, {
@@ -279,13 +275,6 @@ export function registerBuiltinTools(refs: AIServiceRefs): void {
279
275
  skillReloadDebounce = null;
280
276
  try {
281
277
  const count = await syncWorkspaceSkills();
282
- const skillsForContext = await discoverWorkspaceSkills(root);
283
- const alwaysContent = await loadAlwaysSkillsContent(skillsForContext);
284
- const skillsXml = buildSkillsSummaryXML(skillsForContext);
285
- if (refs.zhinAgent) {
286
- refs.zhinAgent.setActiveSkillsContext(alwaysContent);
287
- refs.zhinAgent.setSkillsSummaryXML(skillsXml);
288
- }
289
278
  await triggerAIHook(createAIHookEvent('agent', 'skills-reloaded', undefined, { skillCount: count }));
290
279
  if (count >= 0) logger.info(`[技能热重载] 已更新,工作区技能: ${count}`);
291
280
  } catch (e: any) {
@@ -94,7 +94,7 @@ export interface ZhinAgentConfig {
94
94
  }
95
95
 
96
96
  export const DEFAULT_CONFIG: Required<ZhinAgentConfig> = {
97
- persona: 'You are a helpful AI assistant. You can use tools to help the user. Reply in the language specified in [User profile] (key: language or preferred_language), or in the same language as the user\'s message if not set.',
97
+ persona: 'You are Zhin, an intelligent IM bot assistant that helps users with tasks through conversation. Use tools available to you to assist the user. You are running inside the Zhin.js framework.',
98
98
  maxIterations: 5,
99
99
  timeout: 60_000,
100
100
  preExecTimeout: 10_000,
@@ -1,15 +1,24 @@
1
1
  /**
2
2
  * ZhinAgent 执行策略 — bash 命令的安全检查与工具包装
3
+ *
4
+ * 参考 Claude Code bashPermissions.ts 的纵深防御策略:
5
+ * 1. 危险命令黑名单 — 即使 full 模式也阻止解释器/提权命令
6
+ * 2. 环境变量前缀剥离 — `FOO=bar cmd` → 按 `cmd` 做白名单匹配
7
+ * 3. Safe wrapper 剥离 — `timeout 10 cmd` → 按 `cmd` 做匹配
8
+ * 4. 复合命令拆分 — `&&` `||` `;` 逐段独立检查,deny 优先
9
+ * 5. 只读命令自动放行 — 与 file-policy classifyBashCommand 集成
10
+ * 6. ask_user 集成 — execAsk=true 时返回需审批标记(而非无法交互的抛错)
3
11
  */
4
12
 
5
13
  import type { AgentTool } from '@zhin.js/core';
6
14
  import type { ZhinAgentConfig } from './config.js';
15
+ import { classifyBashCommand } from '../file-policy.js';
7
16
 
8
17
  // ── 预设命令白名单 ──────────────────────────────────────────────────
9
18
 
10
- const PRESET_READONLY = ['ls', 'cat', 'pwd', 'date', 'whoami', 'grep', 'find', 'head', 'tail', 'wc'];
11
- const PRESET_NETWORK = [...PRESET_READONLY, 'curl', 'wget', 'ping', 'dig'];
12
- const PRESET_DEVELOPMENT = [...PRESET_NETWORK, 'npm', 'npx', 'node', 'git', 'gh', 'python', 'python3', 'pip', 'pnpm', 'yarn'];
19
+ const PRESET_READONLY = ['ls', 'cat', 'pwd', 'date', 'whoami', 'grep', 'find', 'head', 'tail', 'wc', 'stat', 'file'];
20
+ const PRESET_NETWORK = [...PRESET_READONLY, 'curl', 'wget', 'ping', 'dig', 'nslookup', 'host'];
21
+ const PRESET_DEVELOPMENT = [...PRESET_NETWORK, 'npm', 'npx', 'node', 'git', 'gh', 'python', 'python3', 'pip', 'pnpm', 'yarn', 'tsc', 'bun'];
13
22
 
14
23
  export const EXEC_PRESETS: Record<string, string[]> = {
15
24
  readonly: PRESET_READONLY,
@@ -17,6 +26,122 @@ export const EXEC_PRESETS: Record<string, string[]> = {
17
26
  development: PRESET_DEVELOPMENT,
18
27
  };
19
28
 
29
+ // ── 危险命令黑名单(参考 Claude Code DANGEROUS_COMMANDS)──────────────
30
+
31
+ /**
32
+ * 即使在 full 模式下也会被阻止的危险命令。
33
+ * 这些命令可以执行任意代码、提权或造成不可逆破坏。
34
+ */
35
+ const DANGEROUS_COMMANDS: ReadonlySet<string> = new Set([
36
+ // 提权
37
+ 'sudo', 'su', 'doas',
38
+ // Shell 元命令 — 可执行任意代码
39
+ 'eval', 'exec',
40
+ // 系统级破坏
41
+ 'dd', 'mkfs', 'fdisk', 'parted',
42
+ // 进程注入
43
+ 'gdb', 'strace', 'ltrace', 'ptrace',
44
+ // 环境注入(敏感变量可被设置)
45
+ 'export',
46
+ ]);
47
+
48
+ /**
49
+ * 检查命令是否在危险黑名单中。
50
+ */
51
+ export function isDangerousCommand(cmdName: string): boolean {
52
+ return DANGEROUS_COMMANDS.has(cmdName);
53
+ }
54
+
55
+ // ── 环境变量前缀剥离(参考 Claude Code stripEnvVars)──────────────
56
+
57
+ /**
58
+ * 剥离命令前面的 `KEY=value` 环境变量前缀。
59
+ * 例如 `FOO=bar BAZ=1 curl http://...` → `curl http://...`
60
+ *
61
+ * 只剥离安全的 key=value 对,不剥离含特殊字符的值(可能是注入)。
62
+ */
63
+ export function stripEnvVarPrefix(command: string): string {
64
+ // env 前缀环境变量格式: WORD=VALUE (VALUE 可以被引号或不含空格的字符串)
65
+ return command.replace(
66
+ /^(\s*[A-Za-z_][A-Za-z0-9_]*=(('[^']*'|"[^"]*"|[^\s;|&]*))\s*)+/,
67
+ '',
68
+ ).trim();
69
+ }
70
+
71
+ // ── Safe wrapper 剥离(参考 Claude Code stripSafeWrappers)──────────
72
+
73
+ /**
74
+ * Safe wrapper 命令列表 — 这些命令本身是安全的"包装器",
75
+ * 真正需要检查的是它们后面的实际命令。
76
+ */
77
+ const SAFE_WRAPPERS: ReadonlySet<string> = new Set([
78
+ 'timeout', 'time', 'nice', 'nohup', 'ionice', 'stdbuf', 'unbuffer',
79
+ ]);
80
+
81
+ /**
82
+ * 剥离命令前面的 safe wrapper(如 `timeout 10`、`nice -n 5`)。
83
+ * 只剥离 wrapper + 它的标志/参数(数字、-flag 形式),直到遇到实际命令。
84
+ */
85
+ export function stripSafeWrappers(command: string): string {
86
+ let remaining = command.trim();
87
+ let changed = true;
88
+ // 防止无限循环,最多剥离 5 层
89
+ let maxIter = 5;
90
+ while (changed && maxIter-- > 0) {
91
+ changed = false;
92
+ const tokens = remaining.split(/\s+/);
93
+ if (tokens.length < 2) break;
94
+ if (SAFE_WRAPPERS.has(tokens[0])) {
95
+ // 跳过 wrapper 本身和它的参数(-flag 或纯数字/duration)
96
+ let i = 1;
97
+ while (i < tokens.length && /^(-[A-Za-z0-9]|[0-9]+[smhd]?$)/.test(tokens[i])) {
98
+ i++;
99
+ }
100
+ if (i < tokens.length) {
101
+ remaining = tokens.slice(i).join(' ');
102
+ changed = true;
103
+ }
104
+ }
105
+ }
106
+ return remaining;
107
+ }
108
+
109
+ // ── 复合命令拆分(参考 Claude Code compound command checking)──────
110
+
111
+ /**
112
+ * 将复合命令按 `&&`, `||`, `;` 拆分为独立子命令。
113
+ * 管道 `|` 不拆分 — 管道中的只读性由 classifyBashCommand 判断。
114
+ *
115
+ * 注意:不处理 subshell `$(...)` 和反引号 — 这些场景由危险黑名单覆盖。
116
+ */
117
+ export function splitCompoundCommand(command: string): string[] {
118
+ // 按 &&, ||, ; 拆分,保留管道作为整体
119
+ return command.split(/\s*(?:&&|\|\||;)\s*/).map(s => s.trim()).filter(Boolean);
120
+ }
121
+
122
+ /**
123
+ * 从命令字符串中提取实际的可执行程序名。
124
+ * 先剥离环境变量前缀和 safe wrapper。
125
+ */
126
+ export function extractCommandName(command: string): string {
127
+ const stripped = stripSafeWrappers(stripEnvVarPrefix(command));
128
+ // 取第一个非管道 token
129
+ const name = stripped.split(/[\s|]/)[0] || '';
130
+ return name;
131
+ }
132
+
133
+ // ── 策略检查结果 ────────────────────────────────────────────────────
134
+
135
+ export interface ExecPolicyResult {
136
+ allowed: boolean;
137
+ /** 如果不允许,拒绝原因 */
138
+ reason?: string;
139
+ /** 如果需要用户确认(execAsk=true 且命令不在白名单但也不在黑名单) */
140
+ needsApproval?: boolean;
141
+ }
142
+
143
+ // ── 核心检查函数 ────────────────────────────────────────────────────
144
+
20
145
  /**
21
146
  * Resolves the effective allowlist by merging preset commands with custom allowlist.
22
147
  */
@@ -29,21 +154,34 @@ export function resolveExecAllowlist(config: Required<ZhinAgentConfig>): string[
29
154
  }
30
155
 
31
156
  /**
32
- * Check if a bash command is allowed under the current exec policy.
33
- * Throws an Error when the command is denied.
157
+ * 检查单条子命令是否允许执行。
158
+ * 内部函数 不做复合命令拆分。
34
159
  */
35
- export function checkExecPolicy(config: Required<ZhinAgentConfig>, command: string): void {
36
- const security = config.execSecurity ?? 'deny';
37
- if (security === 'full') return;
38
- if (security === 'deny') {
39
- throw new Error('当前配置禁止执行 Shell 命令(execSecurity=deny)。如需开放请在配置中设置 ai.agent.execSecurity。');
160
+ function checkSingleCommand(
161
+ cmdName: string,
162
+ fullSubCommand: string,
163
+ allowlist: string[],
164
+ security: string,
165
+ execAsk: boolean,
166
+ ): ExecPolicyResult {
167
+ // 1. 危险黑名单 — 任何模式都拒绝
168
+ if (isDangerousCommand(cmdName)) {
169
+ return { allowed: false, reason: `拒绝执行危险命令「${cmdName}」— 该命令可提权或执行任意代码。` };
40
170
  }
41
- // allowlist
42
- const list = resolveExecAllowlist(config);
43
- const cmd = (command || '').trim();
44
- // 提取命令的第一个 token(实际可执行程序名)进行白名单匹配
45
- const cmdName = cmd.split(/[\s;|&]/)[0];
46
- const allowed = list.some(pattern => {
171
+
172
+ // 2. full 模式 — 通过黑名单后全部放行
173
+ if (security === 'full') {
174
+ return { allowed: true };
175
+ }
176
+
177
+ // 3. 只读命令自动放行(与 file-policy classifyBashCommand 集成)
178
+ const classification = classifyBashCommand(fullSubCommand);
179
+ if (classification.isReadOnly) {
180
+ return { allowed: true };
181
+ }
182
+
183
+ // 4. 白名单匹配
184
+ const allowed = allowlist.some(pattern => {
47
185
  try {
48
186
  const re = new RegExp(`^${pattern}$`);
49
187
  return re.test(cmdName);
@@ -51,18 +189,78 @@ export function checkExecPolicy(config: Required<ZhinAgentConfig>, command: stri
51
189
  return cmdName === pattern;
52
190
  }
53
191
  });
54
- if (!allowed) {
55
- const ask = config.execAsk;
56
- throw new Error(
57
- ask
58
- ? '该命令不在允许列表中,需要审批后执行。当前版本请将命令加入 ai.agent.execAllowlist 或联系管理员。'
59
- : '该命令不在允许列表中,已被拒绝执行。可将允许的命令模式加入 ai.agent.execAllowlist。',
60
- );
192
+
193
+ if (allowed) {
194
+ return { allowed: true };
61
195
  }
196
+
197
+ // 5. 需审批或拒绝
198
+ if (execAsk) {
199
+ return {
200
+ allowed: false,
201
+ needsApproval: true,
202
+ reason: `命令「${cmdName}」不在允许列表中,需要用户确认后执行。`,
203
+ };
204
+ }
205
+
206
+ return {
207
+ allowed: false,
208
+ reason: `命令「${cmdName}」不在允许列表中,已被拒绝。可将命令加入 ai.agent.execAllowlist 或改用 execPreset。`,
209
+ };
210
+ }
211
+
212
+ /**
213
+ * Check if a bash command is allowed under the current exec policy.
214
+ * 支持复合命令拆分、环境变量剥离、safe wrapper 剥离、只读自动放行。
215
+ *
216
+ * @returns ExecPolicyResult — 允许/拒绝/需审批
217
+ */
218
+ export function checkExecPolicy(config: Required<ZhinAgentConfig>, command: string): ExecPolicyResult {
219
+ const security = config.execSecurity ?? 'deny';
220
+ if (security === 'deny') {
221
+ return { allowed: false, reason: '当前配置禁止执行 Shell 命令(execSecurity=deny)。如需开放请在配置中设置 ai.agent.execSecurity。' };
222
+ }
223
+
224
+ const allowlist = resolveExecAllowlist(config);
225
+ const execAsk = config.execAsk ?? false;
226
+ const cmd = (command || '').trim();
227
+
228
+ if (!cmd) {
229
+ return { allowed: false, reason: '命令为空' };
230
+ }
231
+
232
+ // 拆分复合命令 — 每段独立检查,deny 优先
233
+ const subCommands = splitCompoundCommand(cmd);
234
+ let pendingApproval: ExecPolicyResult | null = null;
235
+
236
+ for (const sub of subCommands) {
237
+ const cmdName = extractCommandName(sub);
238
+ if (!cmdName) continue;
239
+
240
+ const result = checkSingleCommand(cmdName, sub, allowlist, security, execAsk);
241
+
242
+ // deny 立即返回(deny > ask 优先级)
243
+ if (!result.allowed && !result.needsApproval) {
244
+ return result;
245
+ }
246
+
247
+ // 记录第一个需要审批的
248
+ if (!result.allowed && result.needsApproval && !pendingApproval) {
249
+ pendingApproval = result;
250
+ }
251
+ }
252
+
253
+ // 有需要审批的段
254
+ if (pendingApproval) {
255
+ return pendingApproval;
256
+ }
257
+
258
+ return { allowed: true };
62
259
  }
63
260
 
64
261
  /**
65
262
  * Wrap `bash` tools with exec policy enforcement.
263
+ * 当 execAsk=true 且命令需审批时,返回提示信息而非抛错。
66
264
  */
67
265
  export function applyExecPolicyToTools(config: Required<ZhinAgentConfig>, tools: AgentTool[]): AgentTool[] {
68
266
  return tools.map(t => {
@@ -72,7 +270,14 @@ export function applyExecPolicyToTools(config: Required<ZhinAgentConfig>, tools:
72
270
  ...t,
73
271
  execute: async (args: Record<string, any>) => {
74
272
  const cmd = args?.command != null ? String(args.command) : '';
75
- checkExecPolicy(config, cmd);
273
+ const result = checkExecPolicy(config, cmd);
274
+ if (!result.allowed) {
275
+ if (result.needsApproval) {
276
+ // 返回可读消息让 AI 用 ask_user 向用户确认
277
+ return `⚠️ ${result.reason}\n请使用 ask_user 工具询问用户是否允许执行此命令。`;
278
+ }
279
+ throw new Error(result.reason!);
280
+ }
76
281
  return original(args);
77
282
  },
78
283
  };