@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
@@ -1,116 +1,117 @@
1
1
  /**
2
2
  * AI 内置系统工具
3
3
  *
4
- * 借鉴 OpenClaw/MicroClaw 的实用工具设计,为 ZhinAgent 提供:
5
- *
6
4
  * 文件工具: read_file, write_file, edit_file, list_dir, glob, grep
7
5
  * Shell: bash
8
6
  * 网络: web_search, web_fetch
9
7
  * 计划: todo_read, todo_write
10
8
  * 记忆: read_memory, write_memory (AGENTS.md)
11
9
  * 技能: activate_skill, install_skill
12
- * 会话: session_status, compact_session
13
- * 技能发现: 工作区 skills/ 目录自动扫描
14
- * 引导文件: SOUL.md, TOOLS.md, AGENTS.md 自动加载
10
+ * 交互: ask_user(基于 Prompt 类的用户确认/提问工具)
11
+ *
12
+ * 发现逻辑已拆分到 discover-skills.ts / discover-agents.ts / discover-tools.ts
15
13
  */
16
14
  import * as fs from 'fs';
17
- import * as os from 'os';
18
15
  import * as path from 'path';
19
16
  import { exec } from 'child_process';
20
17
  import { promisify } from 'util';
21
- import { Logger } from '@zhin.js/core';
18
+ import { Logger, Prompt } from '@zhin.js/core';
22
19
  import { ZhinTool } from '@zhin.js/core';
23
- import { assertFileAccess, checkBashCommandSafety, shellEscape } from './file-policy.js';
24
- // 从新模块中 re-export 向后兼容的函数
25
- export { loadSoulPersona, loadToolsGuide, loadAgentsMemory } from './bootstrap.js';
20
+ import { assertFileAccess, checkBashCommandSafety, shellEscape, isBlockedDevicePath, MAX_READ_FILE_SIZE, MAX_EDIT_FILE_SIZE, classifyBashCommand, isFileStale, } from './file-policy.js';
21
+ import { errMsg, expandHome, getDataDir, mergeSkillDirsWithResolver, nodeErrToFileMessage, } from './discovery-utils.js';
22
+ import { checkSkillDeps, extractSkillInstructions } from './discover-skills.js';
26
23
  const execAsync = promisify(exec);
27
24
  const logger = new Logger(null, 'builtin-tools');
28
- function errMsg(e) {
29
- return e instanceof Error ? e.message : String(e);
25
+ // ── 引号归一化 + 模糊匹配(参考 Claude Code FileEditTool/utils.ts) ──
26
+ /** 将弯引号归一化为直引号 */
27
+ function normalizeQuotes(str) {
28
+ return str
29
+ .replace(/\u2018/g, "'") // '
30
+ .replace(/\u2019/g, "'") // '
31
+ .replace(/\u201C/g, '"') // "
32
+ .replace(/\u201D/g, '"'); // "
30
33
  }
31
34
  /**
32
- * 获取数据目录路径
35
+ * 在文件内容中查找字符串,支持精确匹配和引号归一化模糊匹配。
36
+ * 参考 Claude Code `findActualString`。
33
37
  */
34
- function getDataDir() {
35
- const dir = path.join(process.cwd(), 'data');
36
- fs.mkdirSync(dir, { recursive: true });
37
- return dir;
38
- }
39
- /** Workspace / ~/.zhin / data 下 skills 根目录(与 activate_skill 扫描顺序一致的前缀) */
40
- function buildStandardSkillDirs() {
41
- return [
42
- path.join(process.cwd(), 'skills'),
43
- path.join(os.homedir(), '.zhin', 'skills'),
44
- path.join(getDataDir(), 'skills'),
45
- ];
38
+ function findActualStringInFile(fileContent, searchString) {
39
+ // 精确匹配
40
+ const exactCount = fileContent.split(searchString).length - 1;
41
+ if (exactCount > 0) {
42
+ return { actual: searchString, count: exactCount, wasNormalized: false };
43
+ }
44
+ // 引号归一化匹配
45
+ const normalizedSearch = normalizeQuotes(searchString);
46
+ const normalizedFile = normalizeQuotes(fileContent);
47
+ const idx = normalizedFile.indexOf(normalizedSearch);
48
+ if (idx !== -1) {
49
+ // 提取文件中实际的字符串(保留原始弯引号)
50
+ const actual = fileContent.substring(idx, idx + searchString.length);
51
+ const normalizedCount = normalizedFile.split(normalizedSearch).length - 1;
52
+ return { actual, count: normalizedCount, wasNormalized: true };
53
+ }
54
+ return null;
46
55
  }
47
56
  /**
48
- * 从根插件树收集:根插件与**直接子插件**包目录下的 `skills/`(其下为 `<name>/SKILL.md`)
57
+ * new_string 中的直引号替换为文件中原始的弯引号风格。
58
+ * 参考 Claude Code `preserveQuoteStyle`。
49
59
  */
50
- export function collectPluginSkillSearchRoots(root) {
51
- if (!root)
52
- return [];
53
- const dirs = [];
54
- const push = (d) => {
55
- if (d && !dirs.includes(d))
56
- dirs.push(d);
57
- };
58
- const fromPlugin = (p) => {
59
- if (!p?.filePath)
60
- return;
61
- const dir = path.dirname(p.filePath);
62
- push(path.join(dir, 'skills'));
63
- // Also check package root when filePath is under src/ or lib/
64
- const dirName = path.basename(dir);
65
- if (dirName === 'src' || dirName === 'lib') {
66
- push(path.join(path.dirname(dir), 'skills'));
60
+ function preserveQuoteStyleInEdit(oldString, actualOldString, newString) {
61
+ if (oldString === actualOldString)
62
+ return newString;
63
+ const hasDouble = actualOldString.includes('\u201C') || actualOldString.includes('\u201D');
64
+ const hasSingle = actualOldString.includes('\u2018') || actualOldString.includes('\u2019');
65
+ if (!hasDouble && !hasSingle)
66
+ return newString;
67
+ let result = newString;
68
+ if (hasDouble) {
69
+ // 简单启发式:前面是空白/行首时用左引号,否则右引号
70
+ const chars = [...result];
71
+ const out = [];
72
+ for (let i = 0; i < chars.length; i++) {
73
+ if (chars[i] === '"') {
74
+ const prev = i > 0 ? chars[i - 1] : ' ';
75
+ const isOpening = /[\s(\[{]/.test(prev) || i === 0;
76
+ out.push(isOpening ? '\u201C' : '\u201D');
77
+ }
78
+ else {
79
+ out.push(chars[i]);
80
+ }
67
81
  }
68
- };
69
- fromPlugin(root);
70
- for (const child of root.children || []) {
71
- fromPlugin(child);
72
- }
73
- return dirs;
74
- }
75
- /**
76
- * 技能发现与 activate_skill 查找共用:标准目录 + 已加载插件包 skills/
77
- */
78
- export function getSkillSearchDirectories(root) {
79
- const list = [...buildStandardSkillDirs()];
80
- for (const d of collectPluginSkillSearchRoots(root ?? undefined)) {
81
- if (!list.includes(d))
82
- list.push(d);
83
- }
84
- return list;
85
- }
86
- function mergeSkillDirsWithResolver(resolver) {
87
- const list = [...buildStandardSkillDirs()];
88
- for (const d of resolver?.() ?? []) {
89
- if (d && !list.includes(d))
90
- list.push(d);
82
+ result = out.join('');
83
+ }
84
+ if (hasSingle) {
85
+ const chars = [...result];
86
+ const out = [];
87
+ for (let i = 0; i < chars.length; i++) {
88
+ if (chars[i] === "'") {
89
+ const prev = i > 0 ? chars[i - 1] : ' ';
90
+ const next = i < chars.length - 1 ? chars[i + 1] : ' ';
91
+ // 两个字母之间是缩写,用右引号
92
+ if (/\p{L}/u.test(prev) && /\p{L}/u.test(next)) {
93
+ out.push('\u2019');
94
+ }
95
+ else {
96
+ const isOpening = /[\s(\[{]/.test(prev) || i === 0;
97
+ out.push(isOpening ? '\u2018' : '\u2019');
98
+ }
99
+ }
100
+ else {
101
+ out.push(chars[i]);
102
+ }
103
+ }
104
+ result = out.join('');
91
105
  }
92
- return list;
93
- }
94
- /** 展开路径中的 ~ 为实际 home 目录 */
95
- function expandHome(p) {
96
- if (p === '~')
97
- return os.homedir();
98
- if (p.startsWith('~/') || p.startsWith('~\\'))
99
- return path.join(os.homedir(), p.slice(2));
100
- return p;
106
+ return result;
101
107
  }
102
- /** Node 文件错误转为 miniclawd 风格的结构化短句,便于模型区分并重试 */
103
- function nodeErrToFileMessage(err, filePath, kind) {
104
- const e = err;
105
- if (e?.code === 'ENOENT') {
106
- if (kind === 'list')
107
- return `Error: Directory not found: ${filePath}`;
108
- return `Error: File not found: ${filePath}`;
109
- }
110
- if (e?.code === 'EACCES')
111
- return `Error: Permission denied: ${filePath}`;
112
- const action = kind === 'read' ? 'reading file' : kind === 'write' ? 'writing file' : kind === 'edit' ? 'editing file' : 'listing directory';
113
- return `Error ${action}: ${e?.message ?? String(err)}`;
108
+ // ── 图片格式检测(参考 Claude Code FileReadTool imageResizer) ──
109
+ /** 支持的图片扩展名 */
110
+ const IMAGE_EXTENSIONS = new Set([
111
+ '.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.svg', '.ico',
112
+ ]);
113
+ function isImageFile(filePath) {
114
+ return IMAGE_EXTENSIONS.has(path.extname(filePath).toLowerCase());
114
115
  }
115
116
  /**
116
117
  * 创建所有内置系统工具
@@ -120,10 +121,11 @@ export function createBuiltinTools(options) {
120
121
  const skillMaxChars = options?.skillInstructionMaxChars ?? 4000;
121
122
  const skillDirList = () => mergeSkillDirsWithResolver(options?.pluginSkillRootsResolver);
122
123
  const skillFileLookup = options?.skillFileLookup;
124
+ const pluginRef = options?.plugin;
123
125
  const tools = [];
124
- // ── read_file(清晰描述 + 强关键词) ──
126
+ // ── read_file(清晰描述 + 强关键词 + 图片检测 + 安全防护) ──
125
127
  tools.push(new ZhinTool('read_file')
126
- .desc('读取指定路径的文件内容。用于查看、打开或读取任意文本文件。')
128
+ .desc('读取指定路径的文件内容。用于查看、打开或读取任意文本文件。图片文件返回 Base64 数据。')
127
129
  .keyword('读文件', '读取文件', '查看文件', '打开文件', '文件内容', 'read file', 'read', 'cat', '查看', '打开')
128
130
  .tag('file', 'read')
129
131
  .kind('file')
@@ -133,8 +135,25 @@ export function createBuiltinTools(options) {
133
135
  .execute(async (args) => {
134
136
  try {
135
137
  const fp = expandHome(args.file_path);
138
+ // 设备路径拦截(参考 Claude Code BLOCKED_DEVICE_PATHS)
139
+ if (isBlockedDevicePath(fp)) {
140
+ return `Error: 禁止读取设备文件 ${fp}(会导致进程挂起或注入攻击)`;
141
+ }
136
142
  assertFileAccess(fp);
137
143
  const stat = await fs.promises.stat(fp);
144
+ // 文件大小限制(参考 Claude Code MAX_EDIT_FILE_SIZE)
145
+ if (stat.size > MAX_READ_FILE_SIZE) {
146
+ return `Error: 文件过大 (${(stat.size / 1024 / 1024).toFixed(1)} MiB),超过 ${MAX_READ_FILE_SIZE / 1024 / 1024} MiB 限制。请使用 offset/limit 分段读取。`;
147
+ }
148
+ // 图片文件检测(参考 Claude Code FileReadTool 的图片处理)
149
+ if (isImageFile(fp)) {
150
+ const buffer = await fs.promises.readFile(fp);
151
+ const ext = path.extname(fp).toLowerCase().replace('.', '');
152
+ const mimeType = ext === 'jpg' ? 'jpeg' : ext === 'svg' ? 'svg+xml' : ext;
153
+ const b64 = buffer.toString('base64');
154
+ const sizeKb = (buffer.length / 1024).toFixed(1);
155
+ return `[Image: ${path.basename(fp)}, ${sizeKb} KB, type: image/${mimeType}]\ndata:image/${mimeType};base64,${b64.slice(0, 200)}...(total ${b64.length} chars)`;
156
+ }
138
157
  const content = await fs.promises.readFile(fp, 'utf-8');
139
158
  const lines = content.split('\n');
140
159
  const offset = args.offset ?? 0;
@@ -167,9 +186,9 @@ export function createBuiltinTools(options) {
167
186
  return nodeErrToFileMessage(e, args.file_path, 'write');
168
187
  }
169
188
  }));
170
- // ── edit_file(old_text 必须精确匹配) ──
189
+ // ── edit_file(支持精确匹配 + 引号归一化模糊匹配)──
171
190
  tools.push(new ZhinTool('edit_file')
172
- .desc('在文件中查找并替换一段文本。old_string 必须在文件中精确存在且唯一;建议包含完整行或足够上下文以避免重复匹配。')
191
+ .desc('在文件中查找并替换一段文本。old_string 必须在文件中精确存在且唯一;建议包含完整行或足够上下文以避免重复匹配。支持弯引号/直引号自动归一化。')
173
192
  .keyword('编辑文件', '修改文件', '替换内容', '查找替换', 'edit file', 'edit', '修改', '替换')
174
193
  .tag('file', 'edit')
175
194
  .kind('file')
@@ -180,13 +199,30 @@ export function createBuiltinTools(options) {
180
199
  try {
181
200
  const fp = expandHome(args.file_path);
182
201
  assertFileAccess(fp);
202
+ // 文件大小限制
203
+ const stat = await fs.promises.stat(fp);
204
+ if (stat.size > MAX_EDIT_FILE_SIZE) {
205
+ return `Error: 文件过大 (${(stat.size / 1024 / 1024).toFixed(1)} MiB),超过 ${MAX_EDIT_FILE_SIZE / 1024 / 1024} MiB 限制。`;
206
+ }
207
+ // 记录 mtime 用于防并发覆写
208
+ const mtimeBefore = stat.mtimeMs;
183
209
  const content = await fs.promises.readFile(fp, 'utf-8');
184
- const count = content.split(args.old_string).length - 1;
185
- if (count === 0)
186
- return `Error: old_string not found in file. Make sure it matches exactly.`;
187
- if (count > 1)
188
- return `Warning: old_string appears ${count} times. Please provide more context to make it unique.`;
189
- const newContent = content.replace(args.old_string, args.new_string);
210
+ // 精确匹配 引号归一化模糊匹配
211
+ const matchResult = findActualStringInFile(content, args.old_string);
212
+ if (!matchResult)
213
+ return `Error: old_string not found in file. Make sure it matches exactly (also tried quote normalization).`;
214
+ if (matchResult.count > 1)
215
+ return `Warning: old_string appears ${matchResult.count} times. Please provide more context to make it unique.`;
216
+ // 如果通过引号归一化匹配,保持文件的引号风格
217
+ const effectiveNew = matchResult.wasNormalized
218
+ ? preserveQuoteStyleInEdit(args.old_string, matchResult.actual, args.new_string)
219
+ : args.new_string;
220
+ const newContent = content.replace(matchResult.actual, effectiveNew);
221
+ // 写入前再检查 mtime 防止并发修改
222
+ const currentStat = await fs.promises.stat(fp);
223
+ if (isFileStale(mtimeBefore, currentStat.mtimeMs)) {
224
+ return `Error: 文件 ${fp} 在读取后被外部修改。请重新读取文件后再编辑,避免覆盖他人的修改。`;
225
+ }
190
226
  await fs.promises.writeFile(fp, newContent, 'utf-8');
191
227
  const oldLines = args.old_string.split('\n');
192
228
  const newLines = args.new_string.split('\n');
@@ -249,25 +285,76 @@ export function createBuiltinTools(options) {
249
285
  return `Error: ${errMsg(e)}`;
250
286
  }
251
287
  }));
252
- // ── grep ──
288
+ // ── grep(支持上下文行、大小写、多行、ripgrep 自动检测) ──
253
289
  tools.push(new ZhinTool('grep')
254
- .desc('按正则搜索文件内容,返回匹配行和行号')
255
- .keyword('搜索', '查找内容', 'grep', '正则')
290
+ .desc('按正则搜索文件内容,返回匹配行和行号。优先使用 ripgrep (rg),回退到 grep。')
291
+ .keyword('搜索', '查找内容', 'grep', '正则', 'rg', 'ripgrep')
256
292
  .tag('search', 'regex')
257
293
  .kind('file')
258
294
  .param('pattern', { type: 'string', description: '正则表达式' }, true)
259
295
  .param('path', { type: 'string', description: '搜索路径(默认 .)' })
260
296
  .param('include', { type: 'string', description: '文件类型过滤(如 *.ts)' })
297
+ .param('context', { type: 'number', description: '匹配行上下文行数(-C 参数)' })
298
+ .param('before', { type: 'number', description: '匹配行之前显示行数(-B 参数)' })
299
+ .param('after', { type: 'number', description: '匹配行之后显示行数(-A 参数)' })
300
+ .param('ignore_case', { type: 'boolean', description: '大小写不敏感搜索(-i 参数)' })
301
+ .param('multiline', { type: 'boolean', description: '多行模式,. 匹配换行(仅 ripgrep 支持)' })
302
+ .param('limit', { type: 'number', description: '最多返回结果行数(默认 50)' })
261
303
  .execute(async (args) => {
262
304
  try {
263
305
  const searchPath = args.path || '.';
264
306
  assertFileAccess(path.resolve(process.cwd(), searchPath));
265
- // 安全转义 pattern 和 include 参数防止命令注入
266
307
  const safePattern = shellEscape(args.pattern);
267
308
  const safePath = shellEscape(searchPath);
268
- const includeFlag = args.include ? `--include=${shellEscape(args.include)}` : '';
269
- const { stdout } = await execAsync(`grep -rn ${includeFlag} ${safePattern} ${safePath} 2>/dev/null | head -50`, { cwd: process.cwd() });
270
- return stdout.trim() || `No matches for '${args.pattern}'`;
309
+ const limit = args.limit ?? 50;
310
+ // 检测 ripgrep 是否可用
311
+ let useRipgrep = false;
312
+ try {
313
+ await execAsync('rg --version', { timeout: 3000 });
314
+ useRipgrep = true;
315
+ }
316
+ catch { /* ripgrep 不可用,回退到 grep */ }
317
+ let cmd;
318
+ if (useRipgrep) {
319
+ // ripgrep 命令构建
320
+ const rgFlags = ['-n']; // 行号
321
+ if (args.ignore_case)
322
+ rgFlags.push('-i');
323
+ if (args.multiline)
324
+ rgFlags.push('-U', '--multiline-dotall');
325
+ if (args.context)
326
+ rgFlags.push(`-C${args.context}`);
327
+ else {
328
+ if (args.before)
329
+ rgFlags.push(`-B${args.before}`);
330
+ if (args.after)
331
+ rgFlags.push(`-A${args.after}`);
332
+ }
333
+ if (args.include)
334
+ rgFlags.push(`--glob=${shellEscape(args.include)}`);
335
+ cmd = `rg ${rgFlags.join(' ')} ${safePattern} ${safePath} 2>/dev/null | head -${limit}`;
336
+ }
337
+ else {
338
+ // 传统 grep 回退
339
+ const grepFlags = ['-rn'];
340
+ if (args.ignore_case)
341
+ grepFlags.push('-i');
342
+ if (args.context)
343
+ grepFlags.push(`-C${args.context}`);
344
+ else {
345
+ if (args.before)
346
+ grepFlags.push(`-B${args.before}`);
347
+ if (args.after)
348
+ grepFlags.push(`-A${args.after}`);
349
+ }
350
+ const includeFlag = args.include ? `--include=${shellEscape(args.include)}` : '';
351
+ cmd = `grep ${grepFlags.join(' ')} ${includeFlag} ${safePattern} ${safePath} 2>/dev/null | head -${limit}`;
352
+ }
353
+ const { stdout } = await execAsync(cmd, { cwd: process.cwd() });
354
+ const engine = useRipgrep ? '(ripgrep)' : '(grep)';
355
+ return stdout.trim()
356
+ ? `${engine}\n${stdout.trim()}`
357
+ : `No matches for '${args.pattern}' ${engine}`;
271
358
  }
272
359
  catch (e) {
273
360
  const err = e;
@@ -276,9 +363,9 @@ export function createBuiltinTools(options) {
276
363
  return `Error: ${errMsg(e)}`;
277
364
  }
278
365
  }));
279
- // ── bash ──
366
+ // ── bash(安全检查 + 命令读写分类) ──
280
367
  tools.push(new ZhinTool('bash')
281
- .desc('执行 Shell 命令(带超时保护)')
368
+ .desc('执行 Shell 命令(带超时保护和命令分类)。返回结果中会标注命令类型(只读/搜索/写入)。')
282
369
  .keyword('执行', '运行', '命令', '终端', 'shell', 'bash')
283
370
  .tag('shell', 'exec')
284
371
  .kind('shell')
@@ -293,33 +380,47 @@ export function createBuiltinTools(options) {
293
380
  const safety = checkBashCommandSafety(cmd);
294
381
  if (!safety.safe)
295
382
  return `Error: ${safety.reason}`;
383
+ // 命令读写分类
384
+ const classification = classifyBashCommand(cmd);
296
385
  const { stdout, stderr } = await execAsync(cmd, {
297
386
  cwd: args.cwd || process.cwd(),
298
387
  timeout,
299
388
  maxBuffer: 1024 * 1024,
300
389
  });
301
390
  let result = '';
391
+ const tag = classification.isReadOnly
392
+ ? (classification.isSearch ? '[搜索]' : classification.isList ? '[列出]' : '[只读]')
393
+ : '[执行]';
302
394
  if (stdout.trim())
303
395
  result += `STDOUT:\n${stdout.trim()}`;
304
396
  if (stderr.trim())
305
397
  result += `${result ? '\n' : ''}STDERR:\n${stderr.trim()}`;
306
- return result || '(no output)';
398
+ return `${tag} ${result || '(no output)'}`;
307
399
  }
308
400
  catch (e) {
309
401
  const err = e;
310
402
  return `Error (exit ${err.code || '?'}): ${errMsg(e)}\nSTDOUT:\n${err.stdout || ''}\nSTDERR:\n${err.stderr || ''}`;
311
403
  }
312
404
  }));
313
- // ── web_search(搜索网页,返回标题、URL、摘要) ──
405
+ // ── web_search(搜索网页,返回标题、URL、摘要 + 域名过滤 + 次数限制) ──
406
+ let searchCount = 0;
407
+ const MAX_SEARCH_COUNT = 20; // 单次会话搜索次数上限
314
408
  tools.push(new ZhinTool('web_search')
315
- .desc('在互联网上搜索,返回匹配的标题、URL 和摘要片段。用于查资料、找网页。')
409
+ .desc('在互联网上搜索,返回匹配的标题、URL 和摘要片段。用于查资料、找网页。支持域名过滤。')
316
410
  .keyword('搜索', '网上搜', '网页搜索', '搜索引擎', 'search', 'google', '百度', '查询', '搜一下')
317
411
  .tag('web', 'search')
318
412
  .kind('web')
319
413
  .param('query', { type: 'string', description: '搜索关键词或完整查询语句' }, true)
320
414
  .param('limit', { type: 'number', description: '返回结果数量(默认 5,建议 1–10)' })
415
+ .param('allowed_domains', { type: 'array', description: '仅保留这些域名的结果(可选,如 ["github.com", "stackoverflow.com"])' })
416
+ .param('blocked_domains', { type: 'array', description: '排除这些域名的结果(可选)' })
321
417
  .execute(async (args) => {
322
418
  try {
419
+ // 搜索次数限制
420
+ searchCount++;
421
+ if (searchCount > MAX_SEARCH_COUNT) {
422
+ return `Error: 搜索次数已达上限 (${MAX_SEARCH_COUNT})。请使用已获取的信息回答。`;
423
+ }
323
424
  const limit = args.limit ?? 5;
324
425
  const url = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(args.query)}`;
325
426
  const res = await fetch(url, {
@@ -357,37 +458,97 @@ export function createBuiltinTools(options) {
357
458
  results.push({ title, url: href, snippet });
358
459
  }
359
460
  }
360
- if (results.length === 0)
461
+ // 域名过滤
462
+ let filtered = results;
463
+ if (args.allowed_domains?.length) {
464
+ const allowed = new Set(args.allowed_domains.map(d => d.toLowerCase()));
465
+ filtered = filtered.filter(r => {
466
+ try {
467
+ return allowed.has(new URL(r.url).hostname.toLowerCase());
468
+ }
469
+ catch {
470
+ return false;
471
+ }
472
+ });
473
+ }
474
+ if (args.blocked_domains?.length) {
475
+ const blocked = new Set(args.blocked_domains.map(d => d.toLowerCase()));
476
+ filtered = filtered.filter(r => {
477
+ try {
478
+ return !blocked.has(new URL(r.url).hostname.toLowerCase());
479
+ }
480
+ catch {
481
+ return true;
482
+ }
483
+ });
484
+ }
485
+ if (filtered.length === 0)
361
486
  return 'No results found.';
362
- return results.map((r, i) => `${i + 1}. ${r.title}\n URL: ${r.url}\n ${r.snippet}`).join('\n\n');
487
+ return `(${searchCount}/${MAX_SEARCH_COUNT} searches)\n` + filtered.map((r, i) => `${i + 1}. ${r.title}\n URL: ${r.url}\n ${r.snippet}`).join('\n\n');
363
488
  }
364
489
  catch (e) {
365
490
  return `Error: ${errMsg(e)}`;
366
491
  }
367
492
  }));
368
- // ── web_fetch(抓取 URL 并提取正文) ──
493
+ // ── web_fetch(抓取 URL 并提取正文 + SSRF 防护 + 改进的内容提取) ──
369
494
  tools.push(new ZhinTool('web_fetch')
370
- .desc('抓取指定 URL 的网页内容并提取正文(去除广告等),返回可读文本。用于读文章、获取网页内容。')
495
+ .desc('抓取指定 URL 的网页内容并提取正文(去除广告、脚本等),返回可读文本。仅支持 http/https 协议。')
371
496
  .keyword('抓取网页', '打开链接', '获取网页', '读网页', 'fetch', 'url', '链接内容', '网页内容')
372
497
  .tag('web', 'fetch')
373
498
  .kind('web')
374
499
  .param('url', { type: 'string', description: '要抓取的完整 URL(需 http 或 https)' }, true)
500
+ .param('max_length', { type: 'number', description: '最大返回字符数(默认 20480)' })
375
501
  .execute(async (args) => {
376
502
  try {
503
+ // SSRF 防护:仅允许 http/https 协议
504
+ let parsedUrl;
505
+ try {
506
+ parsedUrl = new URL(args.url);
507
+ }
508
+ catch {
509
+ return `Error: 无效的 URL 格式`;
510
+ }
511
+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
512
+ return `Error: 仅支持 http/https 协议,拒绝 ${parsedUrl.protocol}`;
513
+ }
514
+ // 阻止内网地址(SSRF 关键防护)
515
+ const hostname = parsedUrl.hostname.toLowerCase();
516
+ if (hostname === 'localhost' ||
517
+ hostname === '127.0.0.1' ||
518
+ hostname === '::1' ||
519
+ hostname === '0.0.0.0' ||
520
+ hostname.endsWith('.local') ||
521
+ hostname.startsWith('10.') ||
522
+ hostname.startsWith('192.168.') ||
523
+ /^172\.(1[6-9]|2\d|3[01])\./.test(hostname)) {
524
+ return `Error: 禁止访问内网地址 ${hostname}(SSRF 防护)`;
525
+ }
377
526
  const response = await fetch(args.url, {
378
527
  headers: { 'User-Agent': 'Mozilla/5.0 (compatible; ZhinBot/1.0)' },
379
528
  signal: AbortSignal.timeout(15000),
529
+ redirect: 'follow',
380
530
  });
381
531
  if (!response.ok)
382
532
  return `HTTP ${response.status}: ${response.statusText}`;
383
533
  const html = await response.text();
534
+ // 改进的内容提取:去除脚本、样式、导航、页脚、表单等
384
535
  const text = html
385
536
  .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
386
537
  .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
538
+ .replace(/<nav[^>]*>[\s\S]*?<\/nav>/gi, '')
539
+ .replace(/<footer[^>]*>[\s\S]*?<\/footer>/gi, '')
540
+ .replace(/<header[^>]*>[\s\S]*?<\/header>/gi, ' ')
541
+ .replace(/<form[^>]*>[\s\S]*?<\/form>/gi, '')
542
+ .replace(/<!--[\s\S]*?-->/g, '')
387
543
  .replace(/<[^>]+>/g, ' ')
544
+ .replace(/&nbsp;/gi, ' ')
545
+ .replace(/&amp;/g, '&')
546
+ .replace(/&lt;/g, '<')
547
+ .replace(/&gt;/g, '>')
548
+ .replace(/&quot;/g, '"')
388
549
  .replace(/\s+/g, ' ')
389
550
  .trim();
390
- const maxLen = 20 * 1024;
551
+ const maxLen = args.max_length ?? 20 * 1024;
391
552
  return text.length > maxLen ? text.slice(0, maxLen) + '\n...(truncated)' : text;
392
553
  }
393
554
  catch (e) {
@@ -502,7 +663,6 @@ export function createBuiltinTools(options) {
502
663
  const instructions = extractSkillInstructions(args.name, fullContent, skillMaxChars);
503
664
  return depWarning ? `${depWarning}\n\n${instructions}` : instructions;
504
665
  }
505
- // 回退到目录扫描(与 discoverWorkspaceSkills 顺序一致)
506
666
  for (const dir of skillDirList()) {
507
667
  const skillPath = path.join(dir, args.name, 'SKILL.md');
508
668
  if (fs.existsSync(skillPath)) {
@@ -561,633 +721,62 @@ export function createBuiltinTools(options) {
561
721
  return `Error: ${errMsg(e)}`;
562
722
  }
563
723
  }));
564
- return tools;
565
- }
566
- /**
567
- * 检查技能声明的依赖是否在环境中可用;若有缺失返回提示文案,否则返回空字符串
568
- */
569
- async function checkSkillDeps(content) {
570
- const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---/);
571
- if (!fmMatch)
572
- return '';
573
- let jsYaml;
574
- try {
575
- jsYaml = await import('js-yaml');
576
- if (jsYaml.default)
577
- jsYaml = jsYaml.default;
578
- }
579
- catch {
580
- return '';
581
- }
582
- const metadata = jsYaml.load(fmMatch[1]);
583
- if (!metadata)
584
- return '';
585
- const compat = metadata.compatibility || {};
586
- const deps = compat.deps || metadata.deps;
587
- if (!deps || !Array.isArray(deps))
588
- return '';
589
- const missing = [];
590
- for (const dep of deps) {
724
+ // ── ask_user(基于 Prompt 类的用户确认/提问工具) ──
725
+ tools.push(new ZhinTool('ask_user')
726
+ .desc('向用户发送问题,等待用户在聊天中回复。用于需要用户确认、补充信息或做出选择时。支持文本输入、数字输入、是/否确认、选项选择。')
727
+ .keyword('询问', '确认', '提问', '用户输入', 'ask', 'confirm', 'prompt', '选择', '请问')
728
+ .tag('interaction', 'prompt')
729
+ .kind('interaction')
730
+ .param('question', { type: 'string', description: '要向用户提出的问题文本' }, true)
731
+ .param('type', { type: 'string', description: '问题类型: text(文本输入)、number(数字输入)、confirm(是/否确认)、pick(选项选择)。默认 text' })
732
+ .param('options', { type: 'array', description: '选项列表(type=pick 时必填),每项为字符串,如 ["选项A","选项B","选项C"]' })
733
+ .param('default_value', { type: 'string', description: '用户超时未回复时使用的默认值' })
734
+ .param('timeout', { type: 'number', description: '等待用户回复的超时时间(秒),默认 120' })
735
+ .execute(async (args, context) => {
736
+ // 无消息上下文时无法使用(如子任务场景)
737
+ if (!context?.message) {
738
+ return 'Error: 当前上下文没有消息来源,无法向用户提问。请改为在回复中直接询问。';
739
+ }
740
+ if (!pluginRef) {
741
+ return 'Error: 插件实例不可用,无法创建交互式提问。请改为在回复中直接询问。';
742
+ }
743
+ const prompt = new Prompt(pluginRef, context.message);
744
+ const timeoutMs = (args.timeout ?? 120) * 1000;
745
+ const questionType = args.type || 'text';
591
746
  try {
592
- await execAsync(`which ${dep} 2>/dev/null`);
593
- }
594
- catch {
595
- missing.push(dep);
596
- }
597
- }
598
- if (missing.length === 0)
599
- return '';
600
- return `⚠️ 当前环境缺少以下依赖,请先安装后再使用本技能:${missing.join(', ')}`;
601
- }
602
- /**
603
- * 从 SKILL.md 全文中提取精简的执行指令
604
- * 只保留 frontmatter(工具列表)和执行规则,去掉示例、测试场景等冗余内容
605
- * 这样可以大幅减少 token 占用,让小模型能有足够空间继续调用工具
606
- */
607
- function extractSkillInstructions(name, content, maxBodyLen = 4000) {
608
- const lines = [];
609
- lines.push(`Skill '${name}' activated. 请立即根据以下指导执行工具调用:`);
610
- lines.push('');
611
- const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---/);
612
- if (fmMatch) {
613
- const fmContent = fmMatch[1];
614
- const toolsMatch = fmContent.match(/tools:\s*\n((?:\s+-\s+.+\n?)+)/);
615
- if (toolsMatch) {
616
- lines.push('## 可用工具');
617
- lines.push(toolsMatch[0].trim());
618
- lines.push('');
619
- }
620
- }
621
- const bodyAfterFm = fmMatch && fmMatch.index !== undefined
622
- ? content.slice(fmMatch.index + fmMatch[0].length).replace(/^\s+/, '')
623
- : content;
624
- // Priority: "## 快速操作" / "## Quick Actions" summary for small models
625
- const quickActionsMatch = bodyAfterFm.match(/## (?:快速操作|Quick\s*Actions)[\s\S]*?(?=\n## [^\s]|$)/i);
626
- if (quickActionsMatch && maxBodyLen <= 2000) {
627
- lines.push(quickActionsMatch[0].trim());
628
- lines.push('');
629
- lines.push('## 立即行动');
630
- lines.push('根据上面的指导,立即调用工具完成用户请求。禁止重复调用 activate_skill,禁止用文本描述代替实际工具调用。');
631
- return lines.join('\n');
632
- }
633
- const rulesMatch = content.match(/## 执行规则[\s\S]*?(?=\n## [^\s]|$)/);
634
- const workflowMatch = content.match(/## (?:Workflow|Instructions|使用说明)[\s\S]*?(?=\n## [^\s]|$)/);
635
- if (rulesMatch) {
636
- lines.push(rulesMatch[0].trim());
637
- lines.push('');
638
- }
639
- else if (workflowMatch) {
640
- lines.push(workflowMatch[0].trim());
641
- lines.push('');
642
- }
643
- else if (bodyAfterFm.trim()) {
644
- const firstH2 = bodyAfterFm.match(/\n## [^\s]/);
645
- const intro = firstH2 ? bodyAfterFm.slice(0, firstH2.index).trim() : bodyAfterFm.trim();
646
- const quickStartMatch = bodyAfterFm.match(/## (?:快速开始|Quick\s*Start|Getting\s*Started)[\s\S]*?(?=\n## [^\s]|$)/i);
647
- const authMatch = bodyAfterFm.match(/## (?:认证|Authentication|Auth)[\s\S]*?(?=\n## [^\s]|$)/i);
648
- if (quickStartMatch || (intro.length < 200 && bodyAfterFm.length > intro.length)) {
649
- lines.push('## 指导');
650
- lines.push(intro);
651
- lines.push('');
652
- const extra = [];
653
- if (quickStartMatch)
654
- extra.push(quickStartMatch[0].trim());
655
- if (authMatch)
656
- extra.push(authMatch[0].trim());
657
- if (extra.length > 0) {
658
- const joined = extra.join('\n\n');
659
- lines.push(joined.length > maxBodyLen ? joined.slice(0, maxBodyLen) + '\n...(truncated)' : joined);
660
- }
661
- else {
662
- const rest = bodyAfterFm.slice(intro.length).trim();
663
- lines.push(rest.length > maxBodyLen ? rest.slice(0, maxBodyLen) + '\n...(truncated)' : rest);
664
- }
665
- lines.push('');
666
- }
667
- else if (intro) {
668
- lines.push('## 指导');
669
- lines.push(intro);
670
- lines.push('');
671
- }
672
- }
673
- lines.push('## 立即行动');
674
- lines.push('根据上面的指导,立即调用工具完成用户请求。禁止重复调用 activate_skill,禁止用文本描述代替实际工具调用。');
675
- return lines.join('\n');
676
- }
677
- /**
678
- * 扫描技能目录,发现 SKILL.md 技能文件
679
- * 加载顺序:Workspace(cwd/skills)> Local(~/.zhin/skills)> data/skills > 已加载插件包 skills/,同名先发现者优先
680
- * 支持平台/依赖兼容性过滤。内置技能由 create-zhin 在创建项目时写入 skills/summarize 等。
681
- *
682
- * @param root 根插件(可选):用于追加插件包内 `skills/` 扫描,与 `activate_skill` 查找路径一致
683
- */
684
- export async function discoverWorkspaceSkills(root) {
685
- const skills = [];
686
- const seenNames = new Set();
687
- const dataDir = getDataDir();
688
- const skillDirs = getSkillSearchDirectories(root ?? undefined);
689
- // 确保 data/skills 目录存在
690
- const defaultSkillDir = path.join(dataDir, 'skills');
691
- if (!fs.existsSync(defaultSkillDir)) {
692
- fs.mkdirSync(defaultSkillDir, { recursive: true });
693
- logger.debug(`Created skill directory: ${defaultSkillDir}`);
694
- }
695
- for (const skillsDir of skillDirs) {
696
- if (!fs.existsSync(skillsDir))
697
- continue;
698
- let entries;
699
- try {
700
- entries = await fs.promises.readdir(skillsDir, { withFileTypes: true });
701
- }
702
- catch {
703
- continue;
704
- }
705
- for (const entry of entries) {
706
- if (!entry.isDirectory())
707
- continue;
708
- const skillMdPath = path.join(skillsDir, entry.name, 'SKILL.md');
709
- if (!fs.existsSync(skillMdPath))
710
- continue;
711
- try {
712
- const content = await fs.promises.readFile(skillMdPath, 'utf-8');
713
- // 改进的 frontmatter 正则:支持多种换行符、可选的尾部空白
714
- const match = content.match(/^---\s*\n([\s\S]*?)\n---\s*(?:\n|$)/);
715
- if (!match) {
716
- logger.debug(`Skill文件 ${skillMdPath} 没有有效的frontmatter格式`);
717
- continue;
718
- }
719
- let jsYaml;
720
- try {
721
- jsYaml = await import('js-yaml');
722
- if (jsYaml.default)
723
- jsYaml = jsYaml.default;
724
- }
725
- catch (e) {
726
- logger.warn(`Unable to import js-yaml module: ${e}`);
727
- continue;
747
+ switch (questionType) {
748
+ case 'number': {
749
+ const defaultNum = args.default_value != null ? Number(args.default_value) : undefined;
750
+ const result = await prompt.number(args.question, timeoutMs, defaultNum, '输入超时,已取消');
751
+ return String(result);
728
752
  }
729
- const metadata = jsYaml.load(match[1]);
730
- if (!metadata || !metadata.name || !metadata.description) {
731
- logger.debug(`Skill文件 ${skillMdPath} 缺少必需的 name/description 字段`);
732
- continue;
753
+ case 'confirm': {
754
+ const result = await prompt.confirm(args.question, 'yes', timeoutMs, false, '确认超时,已取消');
755
+ return result ? 'yes' : 'no';
733
756
  }
734
- // 平台兼容检查
735
- const compat = metadata.compatibility || {};
736
- if (compat.os && Array.isArray(compat.os)) {
737
- const currentOs = process.platform === 'darwin' ? 'darwin' : process.platform === 'win32' ? 'windows' : 'linux';
738
- if (!compat.os.includes(currentOs)) {
739
- logger.debug(`Skipping skill '${metadata.name}' (unsupported OS)`);
740
- continue;
757
+ case 'pick': {
758
+ if (!args.options?.length) {
759
+ return 'Error: type=pick 时必须提供 options 选项列表';
741
760
  }
761
+ const pickOptions = args.options.map((o) => ({ label: o, value: o }));
762
+ const result = await prompt.pick(args.question, {
763
+ type: 'text',
764
+ options: pickOptions,
765
+ timeout: timeoutMs,
766
+ }, '选择超时,已取消');
767
+ return String(result);
742
768
  }
743
- // 依赖检查:支持 metadata.requires.bins / requires.env 或 compat.deps / metadata.deps
744
- const requiresBins = metadata.requires?.bins || compat.deps || metadata.deps || [];
745
- const requiresEnv = metadata.requires?.env || [];
746
- const binsToCheck = Array.isArray(requiresBins) ? requiresBins : [];
747
- const envToCheck = Array.isArray(requiresEnv) ? requiresEnv : [];
748
- const requiresMissing = [];
749
- for (const bin of binsToCheck) {
750
- try {
751
- await execAsync(`which ${bin} 2>/dev/null`);
752
- }
753
- catch {
754
- requiresMissing.push(`CLI: ${bin}`);
755
- }
756
- }
757
- for (const envKey of envToCheck) {
758
- if (!process.env[envKey]) {
759
- requiresMissing.push(`ENV: ${envKey}`);
760
- }
761
- }
762
- const available = requiresMissing.length === 0;
763
- if (seenNames.has(metadata.name)) {
764
- logger.debug(`Skill '${metadata.name}' 已由先序目录加载,跳过: ${skillMdPath}`);
765
- continue;
769
+ case 'text':
770
+ default: {
771
+ const result = await prompt.text(args.question, timeoutMs, args.default_value || '', '输入超时,已取消');
772
+ return result;
766
773
  }
767
- seenNames.add(metadata.name);
768
- skills.push({
769
- name: metadata.name,
770
- description: metadata.description,
771
- keywords: metadata.keywords || [],
772
- tags: [...(metadata.tags || []), 'workspace-skill'],
773
- toolNames: Array.isArray(metadata.tools) ? metadata.tools : [],
774
- filePath: skillMdPath,
775
- always: Boolean(metadata.always),
776
- available,
777
- requiresMissing: requiresMissing.length > 0 ? requiresMissing : undefined,
778
- });
779
- logger.debug(`Skill发现成功: ${metadata.name}, tools: ${JSON.stringify(metadata.tools || [])}`);
780
- }
781
- catch (e) {
782
- logger.warn(`Failed to parse SKILL.md in ${skillMdPath}:`, e);
783
774
  }
784
775
  }
785
- }
786
- if (skills.length > 0) {
787
- logger.info(`发现 ${skills.length} 个工作区技能: ${skills.map(s => `${s.name}(tools:${(s.toolNames || []).join(',')})`).join(', ')}`);
788
- }
789
- return skills;
790
- }
791
- /**
792
- * 获取 frontmatter 中 always: true 的技能名列表(用于常驻注入 system prompt)
793
- */
794
- export function getAlwaysSkillNames(skills) {
795
- return skills.filter(s => s.always && s.available).map(s => s.name);
796
- }
797
- /**
798
- * 去除 frontmatter,返回正文
799
- */
800
- function stripFrontmatter(content) {
801
- const match = content.match(/^---\s*\n[\s\S]*?\n---\s*(?:\n|$)/);
802
- if (match) {
803
- return content.slice(match[0].length).trim();
804
- }
805
- return content.trim();
806
- }
807
- /**
808
- * 加载 always 技能的正文内容并拼接为「Active Skills」段
809
- */
810
- export async function loadAlwaysSkillsContent(skills) {
811
- const always = skills.filter(s => s.always && s.available);
812
- if (always.length === 0)
813
- return '';
814
- const parts = [];
815
- for (const s of always) {
816
- try {
817
- const content = await fs.promises.readFile(s.filePath, 'utf-8');
818
- const body = stripFrontmatter(content);
819
- parts.push(`### Skill: ${s.name}\n\n${body}`);
820
- }
821
776
  catch (e) {
822
- logger.warn(`Failed to load always skill ${s.name}: ${e.message}`);
823
- }
824
- }
825
- return parts.join('\n\n---\n\n');
826
- }
827
- /** 转义 XML 特殊字符 */
828
- function escapeXml(s) {
829
- return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
830
- }
831
- /**
832
- * 构建技能列表的 XML 摘要,供 model 区分可用/不可用及缺失依赖
833
- */
834
- export function buildSkillsSummaryXML(skills) {
835
- if (skills.length === 0)
836
- return '';
837
- const lines = ['<skills>'];
838
- for (const s of skills) {
839
- const available = s.available !== false;
840
- lines.push(` <skill available="${available}">`);
841
- lines.push(` <name>${escapeXml(s.name)}</name>`);
842
- lines.push(` <description>${escapeXml(s.description)}</description>`);
843
- lines.push(` <location>${escapeXml(s.filePath)}</location>`);
844
- if (!available && s.requiresMissing && s.requiresMissing.length > 0) {
845
- lines.push(` <requires>${escapeXml(s.requiresMissing.join(', '))}</requires>`);
846
- }
847
- lines.push(' </skill>');
848
- }
849
- lines.push('</skills>');
850
- return lines.join('\n');
851
- }
852
- /**
853
- * 扫描 agents/ 目录,发现 *.agent.md 文件
854
- * 加载顺序与 skills 一致:Workspace > ~/.zhin > data > 插件包
855
- * 同名先发现者优先
856
- */
857
- export async function discoverWorkspaceAgents(root) {
858
- const agents = [];
859
- const seenNames = new Set();
860
- // 构建扫描目录:标准目录的 agents/ + 插件包的 agents/
861
- const agentDirs = [
862
- path.join(process.cwd(), 'agents'),
863
- path.join(os.homedir(), '.zhin', 'agents'),
864
- path.join(getDataDir(), 'agents'),
865
- ];
866
- if (root) {
867
- const addPluginDir = (p) => {
868
- if (!p?.filePath)
869
- return;
870
- const dir = path.dirname(p.filePath);
871
- const d = path.join(dir, 'agents');
872
- if (!agentDirs.includes(d))
873
- agentDirs.push(d);
874
- // Also check package root when filePath is under src/ or lib/
875
- const dirName = path.basename(dir);
876
- if (dirName === 'src' || dirName === 'lib') {
877
- const d2 = path.join(path.dirname(dir), 'agents');
878
- if (!agentDirs.includes(d2))
879
- agentDirs.push(d2);
880
- }
881
- };
882
- addPluginDir(root);
883
- for (const child of root.children || []) {
884
- addPluginDir(child);
885
- }
886
- }
887
- for (const agentsDir of agentDirs) {
888
- if (!fs.existsSync(agentsDir))
889
- continue;
890
- let entries;
891
- try {
892
- entries = await fs.promises.readdir(agentsDir, { withFileTypes: true });
893
- }
894
- catch {
895
- continue;
896
- }
897
- for (const entry of entries) {
898
- // 支持两种结构:
899
- // 1. agents/<name>.agent.md(扁平文件)
900
- // 2. agents/<name>/<name>.agent.md(目录结构)
901
- let agentMdPath;
902
- if (entry.isFile() && entry.name.endsWith('.agent.md')) {
903
- agentMdPath = path.join(agentsDir, entry.name);
904
- }
905
- else if (entry.isDirectory()) {
906
- const nested = path.join(agentsDir, entry.name, `${entry.name}.agent.md`);
907
- if (fs.existsSync(nested)) {
908
- agentMdPath = nested;
909
- }
910
- }
911
- if (!agentMdPath)
912
- continue;
913
- try {
914
- const content = await fs.promises.readFile(agentMdPath, 'utf-8');
915
- const match = content.match(/^---\s*\n([\s\S]*?)\n---\s*(?:\n|$)/);
916
- if (!match) {
917
- logger.debug(`Agent文件 ${agentMdPath} 没有有效的frontmatter格式`);
918
- continue;
919
- }
920
- let jsYaml;
921
- try {
922
- jsYaml = await import('js-yaml');
923
- if (jsYaml.default)
924
- jsYaml = jsYaml.default;
925
- }
926
- catch (e) {
927
- logger.warn(`Unable to import js-yaml module: ${e}`);
928
- continue;
929
- }
930
- const metadata = jsYaml.load(match[1]);
931
- if (!metadata || !metadata.name || !metadata.description) {
932
- logger.debug(`Agent文件 ${agentMdPath} 缺少必需的 name/description 字段`);
933
- continue;
934
- }
935
- if (seenNames.has(metadata.name)) {
936
- logger.debug(`Agent '${metadata.name}' 已由先序目录加载,跳过: ${agentMdPath}`);
937
- continue;
938
- }
939
- seenNames.add(metadata.name);
940
- agents.push({
941
- name: metadata.name,
942
- description: metadata.description,
943
- keywords: metadata.keywords || [],
944
- tags: metadata.tags || [],
945
- toolNames: Array.isArray(metadata.tools) ? metadata.tools : [],
946
- filePath: agentMdPath,
947
- model: metadata.model,
948
- provider: metadata.provider,
949
- maxIterations: typeof metadata.maxIterations === 'number' ? metadata.maxIterations : undefined,
950
- });
951
- logger.debug(`Agent发现成功: ${metadata.name}`);
952
- }
953
- catch (e) {
954
- logger.warn(`Failed to parse agent.md in ${agentMdPath}:`, e);
955
- }
956
- }
957
- }
958
- if (agents.length > 0) {
959
- logger.info(`发现 ${agents.length} 个工作区 Agent 预设: ${agents.map(a => a.name).join(', ')}`);
960
- }
961
- return agents;
962
- }
963
- /**
964
- * 从根插件树收集:根插件与直接子插件包目录下的 `tools/`
965
- */
966
- export function collectPluginToolSearchRoots(root) {
967
- if (!root)
968
- return [];
969
- const dirs = [];
970
- const push = (d) => {
971
- if (d && !dirs.includes(d))
972
- dirs.push(d);
973
- };
974
- const fromPlugin = (p) => {
975
- if (!p?.filePath)
976
- return;
977
- const dir = path.dirname(p.filePath);
978
- push(path.join(dir, 'tools'));
979
- // Also check package root when filePath is under src/ or lib/
980
- const dirName = path.basename(dir);
981
- if (dirName === 'src' || dirName === 'lib') {
982
- push(path.join(path.dirname(dir), 'tools'));
983
- }
984
- };
985
- fromPlugin(root);
986
- for (const child of root.children || []) {
987
- fromPlugin(child);
988
- }
989
- return dirs;
990
- }
991
- /**
992
- * 获取所有 tool 搜索目录(标准目录 + 插件包 tools/)
993
- */
994
- export function getToolSearchDirectories(root) {
995
- const list = [
996
- path.join(process.cwd(), 'tools'),
997
- path.join(os.homedir(), '.zhin', 'tools'),
998
- path.join(getDataDir(), 'tools'),
999
- ];
1000
- for (const d of collectPluginToolSearchRoots(root ?? undefined)) {
1001
- if (!list.includes(d))
1002
- list.push(d);
1003
- }
1004
- return list;
1005
- }
1006
- /**
1007
- * 将简写参数定义转换为 ToolParametersSchema
1008
- */
1009
- function shorthandToSchema(params) {
1010
- const properties = {};
1011
- const required = [];
1012
- for (const [key, param] of Object.entries(params)) {
1013
- properties[key] = {
1014
- type: param.type || 'string',
1015
- description: param.description || key,
1016
- };
1017
- if (param.enum)
1018
- properties[key].enum = param.enum;
1019
- if (param.default !== undefined)
1020
- properties[key].default = param.default;
1021
- if (param.required)
1022
- required.push(key);
1023
- }
1024
- return { type: 'object', properties, required: required.length > 0 ? required : undefined };
1025
- }
1026
- /**
1027
- * 加载 handler 文件(动态 import)
1028
- * @returns execute 函数, 或 undefined(加载失败)
1029
- */
1030
- async function loadToolHandler(handlerPath, toolMdPath) {
1031
- const resolved = path.resolve(path.dirname(toolMdPath), handlerPath);
1032
- if (!fs.existsSync(resolved)) {
1033
- logger.warn(`Tool handler 文件不存在: ${resolved}`);
1034
- return undefined;
1035
- }
1036
- try {
1037
- const fileUrl = `file://${resolved}?t=${Date.now()}`;
1038
- const mod = await import(fileUrl);
1039
- const fn = mod.default || mod;
1040
- if (typeof fn !== 'function') {
1041
- logger.warn(`Tool handler 未导出函数: ${resolved}`);
1042
- return undefined;
777
+ return `用户未响应或输入错误: ${errMsg(e)}`;
1043
778
  }
1044
- return fn;
1045
- }
1046
- catch (e) {
1047
- logger.warn(`Tool handler 加载失败 (${resolved}): ${errMsg(e)}`);
1048
- return undefined;
1049
- }
1050
- }
1051
- /**
1052
- * 从 body 构建 prompt 模板执行函数
1053
- */
1054
- function buildTemplateExecute(body) {
1055
- return (args) => body.replace(/\{\{(\w+)\}\}/g, (_, k) => {
1056
- const val = args[k];
1057
- return val !== undefined && val !== null ? String(val) : '';
1058
- });
1059
- }
1060
- /**
1061
- * 扫描 tools/ 目录,发现 *.tool.md 文件
1062
- * 加载顺序与 skills/agents 一致:Workspace > ~/.zhin > data > 插件包
1063
- * 同名先发现者优先
1064
- */
1065
- export async function discoverWorkspaceTools(root) {
1066
- const tools = [];
1067
- const seenNames = new Set();
1068
- const toolDirs = getToolSearchDirectories(root);
1069
- for (const toolsDir of toolDirs) {
1070
- if (!fs.existsSync(toolsDir))
1071
- continue;
1072
- let entries;
1073
- try {
1074
- entries = await fs.promises.readdir(toolsDir, { withFileTypes: true });
1075
- }
1076
- catch {
1077
- continue;
1078
- }
1079
- for (const entry of entries) {
1080
- // 支持两种结构:
1081
- // 1. tools/<name>.tool.md(扁平文件)
1082
- // 2. tools/<name>/<name>.tool.md(目录结构,允许放 handler.ts)
1083
- let toolMdPath;
1084
- if (entry.isFile() && entry.name.endsWith('.tool.md')) {
1085
- toolMdPath = path.join(toolsDir, entry.name);
1086
- }
1087
- else if (entry.isDirectory()) {
1088
- const nested = path.join(toolsDir, entry.name, `${entry.name}.tool.md`);
1089
- if (fs.existsSync(nested)) {
1090
- toolMdPath = nested;
1091
- }
1092
- }
1093
- if (!toolMdPath)
1094
- continue;
1095
- try {
1096
- const content = await fs.promises.readFile(toolMdPath, 'utf-8');
1097
- const match = content.match(/^---\s*\n([\s\S]*?)\n---\s*(?:\n|$)/);
1098
- if (!match) {
1099
- logger.debug(`Tool文件 ${toolMdPath} 没有有效的frontmatter格式`);
1100
- continue;
1101
- }
1102
- let jsYaml;
1103
- try {
1104
- jsYaml = await import('js-yaml');
1105
- if (jsYaml.default)
1106
- jsYaml = jsYaml.default;
1107
- }
1108
- catch (e) {
1109
- logger.warn(`Unable to import js-yaml module: ${e}`);
1110
- continue;
1111
- }
1112
- const metadata = jsYaml.load(match[1]);
1113
- if (!metadata || !metadata.name || !metadata.description) {
1114
- logger.debug(`Tool文件 ${toolMdPath} 缺少必需的 name/description 字段`);
1115
- continue;
1116
- }
1117
- if (seenNames.has(metadata.name)) {
1118
- logger.debug(`Tool '${metadata.name}' 已由先序目录加载,跳过: ${toolMdPath}`);
1119
- continue;
1120
- }
1121
- seenNames.add(metadata.name);
1122
- // 提取 body(frontmatter 之后的内容)
1123
- const body = content.replace(/^---\s*\n[\s\S]*?\n---\s*(?:\n|$)/, '').trim();
1124
- tools.push({
1125
- name: metadata.name,
1126
- description: metadata.description,
1127
- parameters: metadata.parameters || undefined,
1128
- command: metadata.command || undefined,
1129
- platforms: metadata.platforms,
1130
- scopes: metadata.scopes,
1131
- permissionLevel: metadata.permissionLevel,
1132
- tags: metadata.tags || [],
1133
- keywords: metadata.keywords || [],
1134
- kind: metadata.kind,
1135
- hidden: metadata.hidden,
1136
- handler: metadata.handler,
1137
- filePath: toolMdPath,
1138
- templateBody: !metadata.handler && body ? body : undefined,
1139
- });
1140
- logger.debug(`Tool发现成功: ${metadata.name}`);
1141
- }
1142
- catch (e) {
1143
- logger.warn(`Failed to parse tool.md in ${toolMdPath}:`, e);
1144
- }
1145
- }
1146
- }
1147
- if (tools.length > 0) {
1148
- logger.info(`发现 ${tools.length} 个工作区 Tool: ${tools.map(t => t.name).join(', ')}`);
1149
- }
779
+ }));
1150
780
  return tools;
1151
781
  }
1152
- /**
1153
- * 将 ToolMeta 转换为 Tool 对象(包含 execute 函数)
1154
- */
1155
- export async function buildToolFromMeta(meta) {
1156
- // 构建 execute 函数
1157
- let execute;
1158
- if (meta.handler) {
1159
- execute = await loadToolHandler(meta.handler, meta.filePath);
1160
- if (!execute)
1161
- return null;
1162
- }
1163
- else if (meta.templateBody) {
1164
- execute = buildTemplateExecute(meta.templateBody);
1165
- }
1166
- else {
1167
- logger.warn(`Tool '${meta.name}' 既没有 handler 也没有模板 body,跳过`);
1168
- return null;
1169
- }
1170
- // 构建参数 schema
1171
- const parameters = meta.parameters
1172
- ? shorthandToSchema(meta.parameters)
1173
- : { type: 'object', properties: {} };
1174
- return {
1175
- name: meta.name,
1176
- description: meta.description,
1177
- parameters,
1178
- execute,
1179
- tags: meta.tags,
1180
- keywords: meta.keywords,
1181
- platforms: meta.platforms,
1182
- scopes: meta.scopes,
1183
- permissionLevel: meta.permissionLevel,
1184
- hidden: meta.hidden,
1185
- kind: meta.kind,
1186
- command: meta.command ? {
1187
- pattern: meta.command.pattern,
1188
- alias: meta.command.alias,
1189
- examples: meta.command.examples,
1190
- } : undefined,
1191
- };
1192
- }
1193
782
  //# sourceMappingURL=builtin-tools.js.map