@zhin.js/agent 0.0.18 → 0.0.20

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 (45) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +14 -8
  3. package/lib/builtin-tools.d.ts +4 -0
  4. package/lib/builtin-tools.d.ts.map +1 -1
  5. package/lib/builtin-tools.js +436 -29
  6. package/lib/builtin-tools.js.map +1 -1
  7. package/lib/file-policy.d.ts +41 -4
  8. package/lib/file-policy.d.ts.map +1 -1
  9. package/lib/file-policy.js +126 -4
  10. package/lib/file-policy.js.map +1 -1
  11. package/lib/index.d.ts +1 -1
  12. package/lib/index.d.ts.map +1 -1
  13. package/lib/index.js +1 -1
  14. package/lib/index.js.map +1 -1
  15. package/lib/init/create-zhin-agent.d.ts.map +1 -1
  16. package/lib/init/create-zhin-agent.js +1 -0
  17. package/lib/init/create-zhin-agent.js.map +1 -1
  18. package/lib/init/register-ai-trigger.d.ts.map +1 -1
  19. package/lib/init/register-ai-trigger.js +10 -3
  20. package/lib/init/register-ai-trigger.js.map +1 -1
  21. package/lib/init/register-builtin-tools.d.ts.map +1 -1
  22. package/lib/init/register-builtin-tools.js +1 -0
  23. package/lib/init/register-builtin-tools.js.map +1 -1
  24. package/lib/zhin-agent/config.js +1 -1
  25. package/lib/zhin-agent/config.js.map +1 -1
  26. package/lib/zhin-agent/exec-policy.d.ts +48 -2
  27. package/lib/zhin-agent/exec-policy.d.ts.map +1 -1
  28. package/lib/zhin-agent/exec-policy.js +184 -23
  29. package/lib/zhin-agent/exec-policy.js.map +1 -1
  30. package/lib/zhin-agent/prompt.d.ts +14 -0
  31. package/lib/zhin-agent/prompt.d.ts.map +1 -1
  32. package/lib/zhin-agent/prompt.js +192 -45
  33. package/lib/zhin-agent/prompt.js.map +1 -1
  34. package/package.json +3 -3
  35. package/src/builtin-tools.ts +457 -30
  36. package/src/file-policy.ts +152 -4
  37. package/src/index.ts +5 -1
  38. package/src/init/create-zhin-agent.ts +1 -0
  39. package/src/init/register-ai-trigger.ts +15 -3
  40. package/src/init/register-builtin-tools.ts +1 -0
  41. package/src/zhin-agent/config.ts +1 -1
  42. package/src/zhin-agent/exec-policy.ts +229 -24
  43. package/src/zhin-agent/prompt.ts +209 -47
  44. package/tests/exec-policy.test.ts +355 -0
  45. package/tests/file-policy.test.ts +189 -1
@@ -7,6 +7,7 @@
7
7
  * 计划: todo_read, todo_write
8
8
  * 记忆: read_memory, write_memory (AGENTS.md)
9
9
  * 技能: activate_skill, install_skill
10
+ * 交互: ask_user(基于 Prompt 类的用户确认/提问工具)
10
11
  *
11
12
  * 发现逻辑已拆分到 discover-skills.ts / discover-agents.ts / discover-tools.ts
12
13
  */
@@ -14,13 +15,167 @@ import * as fs from 'fs';
14
15
  import * as path from 'path';
15
16
  import { exec } from 'child_process';
16
17
  import { promisify } from 'util';
17
- import { Logger } from '@zhin.js/core';
18
+ import { Logger, Prompt } from '@zhin.js/core';
18
19
  import { ZhinTool } from '@zhin.js/core';
19
- import { assertFileAccess, checkBashCommandSafety, shellEscape } from './file-policy.js';
20
+ import { assertFileAccess, checkBashCommandSafety, shellEscape, isBlockedDevicePath, MAX_READ_FILE_SIZE, MAX_EDIT_FILE_SIZE, classifyBashCommand, isFileStale, } from './file-policy.js';
20
21
  import { errMsg, expandHome, getDataDir, mergeSkillDirsWithResolver, nodeErrToFileMessage, } from './discovery-utils.js';
21
22
  import { checkSkillDeps, extractSkillInstructions } from './discover-skills.js';
22
23
  const execAsync = promisify(exec);
23
24
  const logger = new Logger(null, 'builtin-tools');
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, '"'); // "
33
+ }
34
+ /**
35
+ * 在文件内容中查找字符串,支持精确匹配和引号归一化模糊匹配。
36
+ * 参考 Claude Code `findActualString`。
37
+ */
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;
55
+ }
56
+ /**
57
+ * 将 new_string 中的直引号替换为文件中原始的弯引号风格。
58
+ * 参考 Claude Code `preserveQuoteStyle`。
59
+ */
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
+ }
81
+ }
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('');
105
+ }
106
+ return result;
107
+ }
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());
115
+ }
116
+ // ============================================================================
117
+ // ask_user 辅助函数
118
+ // ============================================================================
119
+ /**
120
+ * 私聊 Owner 场景:使用 Prompt 类直接交互(原有行为)
121
+ */
122
+ async function askViaPrompt(plugin, message, args, questionType, timeoutMs) {
123
+ const prompt = new Prompt(plugin, message);
124
+ try {
125
+ switch (questionType) {
126
+ case 'number': {
127
+ const defaultNum = args.default_value != null ? Number(args.default_value) : undefined;
128
+ const result = await prompt.number(args.question, timeoutMs, defaultNum, '输入超时,已取消');
129
+ return String(result);
130
+ }
131
+ case 'confirm': {
132
+ const result = await prompt.confirm(args.question, 'yes', timeoutMs, false, '确认超时,已取消');
133
+ return result ? 'yes' : 'no';
134
+ }
135
+ case 'pick': {
136
+ if (!args.options?.length) {
137
+ return 'Error: type=pick 时必须提供 options 选项列表';
138
+ }
139
+ const pickOptions = args.options.map((o) => ({ label: o, value: o }));
140
+ const result = await prompt.pick(args.question, {
141
+ type: 'text',
142
+ options: pickOptions,
143
+ timeout: timeoutMs,
144
+ }, '选择超时,已取消');
145
+ return String(result);
146
+ }
147
+ case 'text':
148
+ default: {
149
+ const result = await prompt.text(args.question, timeoutMs, args.default_value || '', '输入超时,已取消');
150
+ return result;
151
+ }
152
+ }
153
+ }
154
+ catch (e) {
155
+ return `Owner 未响应或输入错误: ${errMsg(e)}`;
156
+ }
157
+ }
158
+ /**
159
+ * 将 Owner 私聊回复格式化为对应类型的结果
160
+ */
161
+ function formatOwnerResponse(raw, questionType, args) {
162
+ switch (questionType) {
163
+ case 'confirm':
164
+ return raw.trim().toLowerCase() === 'yes' ? 'yes' : 'no';
165
+ case 'number':
166
+ return String(Number(raw) || 0);
167
+ case 'pick': {
168
+ const idx = Number(raw.trim());
169
+ const options = args.options || [];
170
+ if (idx >= 1 && idx <= options.length)
171
+ return options[idx - 1];
172
+ return raw;
173
+ }
174
+ case 'text':
175
+ default:
176
+ return raw;
177
+ }
178
+ }
24
179
  /**
25
180
  * 创建所有内置系统工具
26
181
  */
@@ -29,10 +184,11 @@ export function createBuiltinTools(options) {
29
184
  const skillMaxChars = options?.skillInstructionMaxChars ?? 4000;
30
185
  const skillDirList = () => mergeSkillDirsWithResolver(options?.pluginSkillRootsResolver);
31
186
  const skillFileLookup = options?.skillFileLookup;
187
+ const pluginRef = options?.plugin;
32
188
  const tools = [];
33
- // ── read_file(清晰描述 + 强关键词) ──
189
+ // ── read_file(清晰描述 + 强关键词 + 图片检测 + 安全防护) ──
34
190
  tools.push(new ZhinTool('read_file')
35
- .desc('读取指定路径的文件内容。用于查看、打开或读取任意文本文件。')
191
+ .desc('读取指定路径的文件内容。用于查看、打开或读取任意文本文件。图片文件返回 Base64 数据。')
36
192
  .keyword('读文件', '读取文件', '查看文件', '打开文件', '文件内容', 'read file', 'read', 'cat', '查看', '打开')
37
193
  .tag('file', 'read')
38
194
  .kind('file')
@@ -42,8 +198,25 @@ export function createBuiltinTools(options) {
42
198
  .execute(async (args) => {
43
199
  try {
44
200
  const fp = expandHome(args.file_path);
201
+ // 设备路径拦截(参考 Claude Code BLOCKED_DEVICE_PATHS)
202
+ if (isBlockedDevicePath(fp)) {
203
+ return `Error: 禁止读取设备文件 ${fp}(会导致进程挂起或注入攻击)`;
204
+ }
45
205
  assertFileAccess(fp);
46
206
  const stat = await fs.promises.stat(fp);
207
+ // 文件大小限制(参考 Claude Code MAX_EDIT_FILE_SIZE)
208
+ if (stat.size > MAX_READ_FILE_SIZE) {
209
+ return `Error: 文件过大 (${(stat.size / 1024 / 1024).toFixed(1)} MiB),超过 ${MAX_READ_FILE_SIZE / 1024 / 1024} MiB 限制。请使用 offset/limit 分段读取。`;
210
+ }
211
+ // 图片文件检测(参考 Claude Code FileReadTool 的图片处理)
212
+ if (isImageFile(fp)) {
213
+ const buffer = await fs.promises.readFile(fp);
214
+ const ext = path.extname(fp).toLowerCase().replace('.', '');
215
+ const mimeType = ext === 'jpg' ? 'jpeg' : ext === 'svg' ? 'svg+xml' : ext;
216
+ const b64 = buffer.toString('base64');
217
+ const sizeKb = (buffer.length / 1024).toFixed(1);
218
+ return `[Image: ${path.basename(fp)}, ${sizeKb} KB, type: image/${mimeType}]\ndata:image/${mimeType};base64,${b64.slice(0, 200)}...(total ${b64.length} chars)`;
219
+ }
47
220
  const content = await fs.promises.readFile(fp, 'utf-8');
48
221
  const lines = content.split('\n');
49
222
  const offset = args.offset ?? 0;
@@ -76,9 +249,9 @@ export function createBuiltinTools(options) {
76
249
  return nodeErrToFileMessage(e, args.file_path, 'write');
77
250
  }
78
251
  }));
79
- // ── edit_file(old_text 必须精确匹配) ──
252
+ // ── edit_file(支持精确匹配 + 引号归一化模糊匹配)──
80
253
  tools.push(new ZhinTool('edit_file')
81
- .desc('在文件中查找并替换一段文本。old_string 必须在文件中精确存在且唯一;建议包含完整行或足够上下文以避免重复匹配。')
254
+ .desc('在文件中查找并替换一段文本。old_string 必须在文件中精确存在且唯一;建议包含完整行或足够上下文以避免重复匹配。支持弯引号/直引号自动归一化。')
82
255
  .keyword('编辑文件', '修改文件', '替换内容', '查找替换', 'edit file', 'edit', '修改', '替换')
83
256
  .tag('file', 'edit')
84
257
  .kind('file')
@@ -89,13 +262,30 @@ export function createBuiltinTools(options) {
89
262
  try {
90
263
  const fp = expandHome(args.file_path);
91
264
  assertFileAccess(fp);
265
+ // 文件大小限制
266
+ const stat = await fs.promises.stat(fp);
267
+ if (stat.size > MAX_EDIT_FILE_SIZE) {
268
+ return `Error: 文件过大 (${(stat.size / 1024 / 1024).toFixed(1)} MiB),超过 ${MAX_EDIT_FILE_SIZE / 1024 / 1024} MiB 限制。`;
269
+ }
270
+ // 记录 mtime 用于防并发覆写
271
+ const mtimeBefore = stat.mtimeMs;
92
272
  const content = await fs.promises.readFile(fp, 'utf-8');
93
- const count = content.split(args.old_string).length - 1;
94
- if (count === 0)
95
- return `Error: old_string not found in file. Make sure it matches exactly.`;
96
- if (count > 1)
97
- return `Warning: old_string appears ${count} times. Please provide more context to make it unique.`;
98
- const newContent = content.replace(args.old_string, args.new_string);
273
+ // 精确匹配 引号归一化模糊匹配
274
+ const matchResult = findActualStringInFile(content, args.old_string);
275
+ if (!matchResult)
276
+ return `Error: old_string not found in file. Make sure it matches exactly (also tried quote normalization).`;
277
+ if (matchResult.count > 1)
278
+ return `Warning: old_string appears ${matchResult.count} times. Please provide more context to make it unique.`;
279
+ // 如果通过引号归一化匹配,保持文件的引号风格
280
+ const effectiveNew = matchResult.wasNormalized
281
+ ? preserveQuoteStyleInEdit(args.old_string, matchResult.actual, args.new_string)
282
+ : args.new_string;
283
+ const newContent = content.replace(matchResult.actual, effectiveNew);
284
+ // 写入前再检查 mtime 防止并发修改
285
+ const currentStat = await fs.promises.stat(fp);
286
+ if (isFileStale(mtimeBefore, currentStat.mtimeMs)) {
287
+ return `Error: 文件 ${fp} 在读取后被外部修改。请重新读取文件后再编辑,避免覆盖他人的修改。`;
288
+ }
99
289
  await fs.promises.writeFile(fp, newContent, 'utf-8');
100
290
  const oldLines = args.old_string.split('\n');
101
291
  const newLines = args.new_string.split('\n');
@@ -158,25 +348,76 @@ export function createBuiltinTools(options) {
158
348
  return `Error: ${errMsg(e)}`;
159
349
  }
160
350
  }));
161
- // ── grep ──
351
+ // ── grep(支持上下文行、大小写、多行、ripgrep 自动检测) ──
162
352
  tools.push(new ZhinTool('grep')
163
- .desc('按正则搜索文件内容,返回匹配行和行号')
164
- .keyword('搜索', '查找内容', 'grep', '正则')
353
+ .desc('按正则搜索文件内容,返回匹配行和行号。优先使用 ripgrep (rg),回退到 grep。')
354
+ .keyword('搜索', '查找内容', 'grep', '正则', 'rg', 'ripgrep')
165
355
  .tag('search', 'regex')
166
356
  .kind('file')
167
357
  .param('pattern', { type: 'string', description: '正则表达式' }, true)
168
358
  .param('path', { type: 'string', description: '搜索路径(默认 .)' })
169
359
  .param('include', { type: 'string', description: '文件类型过滤(如 *.ts)' })
360
+ .param('context', { type: 'number', description: '匹配行上下文行数(-C 参数)' })
361
+ .param('before', { type: 'number', description: '匹配行之前显示行数(-B 参数)' })
362
+ .param('after', { type: 'number', description: '匹配行之后显示行数(-A 参数)' })
363
+ .param('ignore_case', { type: 'boolean', description: '大小写不敏感搜索(-i 参数)' })
364
+ .param('multiline', { type: 'boolean', description: '多行模式,. 匹配换行(仅 ripgrep 支持)' })
365
+ .param('limit', { type: 'number', description: '最多返回结果行数(默认 50)' })
170
366
  .execute(async (args) => {
171
367
  try {
172
368
  const searchPath = args.path || '.';
173
369
  assertFileAccess(path.resolve(process.cwd(), searchPath));
174
- // 安全转义 pattern 和 include 参数防止命令注入
175
370
  const safePattern = shellEscape(args.pattern);
176
371
  const safePath = shellEscape(searchPath);
177
- const includeFlag = args.include ? `--include=${shellEscape(args.include)}` : '';
178
- const { stdout } = await execAsync(`grep -rn ${includeFlag} ${safePattern} ${safePath} 2>/dev/null | head -50`, { cwd: process.cwd() });
179
- return stdout.trim() || `No matches for '${args.pattern}'`;
372
+ const limit = args.limit ?? 50;
373
+ // 检测 ripgrep 是否可用
374
+ let useRipgrep = false;
375
+ try {
376
+ await execAsync('rg --version', { timeout: 3000 });
377
+ useRipgrep = true;
378
+ }
379
+ catch { /* ripgrep 不可用,回退到 grep */ }
380
+ let cmd;
381
+ if (useRipgrep) {
382
+ // ripgrep 命令构建
383
+ const rgFlags = ['-n']; // 行号
384
+ if (args.ignore_case)
385
+ rgFlags.push('-i');
386
+ if (args.multiline)
387
+ rgFlags.push('-U', '--multiline-dotall');
388
+ if (args.context)
389
+ rgFlags.push(`-C${args.context}`);
390
+ else {
391
+ if (args.before)
392
+ rgFlags.push(`-B${args.before}`);
393
+ if (args.after)
394
+ rgFlags.push(`-A${args.after}`);
395
+ }
396
+ if (args.include)
397
+ rgFlags.push(`--glob=${shellEscape(args.include)}`);
398
+ cmd = `rg ${rgFlags.join(' ')} ${safePattern} ${safePath} 2>/dev/null | head -${limit}`;
399
+ }
400
+ else {
401
+ // 传统 grep 回退
402
+ const grepFlags = ['-rn'];
403
+ if (args.ignore_case)
404
+ grepFlags.push('-i');
405
+ if (args.context)
406
+ grepFlags.push(`-C${args.context}`);
407
+ else {
408
+ if (args.before)
409
+ grepFlags.push(`-B${args.before}`);
410
+ if (args.after)
411
+ grepFlags.push(`-A${args.after}`);
412
+ }
413
+ const includeFlag = args.include ? `--include=${shellEscape(args.include)}` : '';
414
+ cmd = `grep ${grepFlags.join(' ')} ${includeFlag} ${safePattern} ${safePath} 2>/dev/null | head -${limit}`;
415
+ }
416
+ const { stdout } = await execAsync(cmd, { cwd: process.cwd() });
417
+ const engine = useRipgrep ? '(ripgrep)' : '(grep)';
418
+ return stdout.trim()
419
+ ? `${engine}\n${stdout.trim()}`
420
+ : `No matches for '${args.pattern}' ${engine}`;
180
421
  }
181
422
  catch (e) {
182
423
  const err = e;
@@ -185,9 +426,9 @@ export function createBuiltinTools(options) {
185
426
  return `Error: ${errMsg(e)}`;
186
427
  }
187
428
  }));
188
- // ── bash ──
429
+ // ── bash(安全检查 + 命令读写分类) ──
189
430
  tools.push(new ZhinTool('bash')
190
- .desc('执行 Shell 命令(带超时保护)')
431
+ .desc('执行 Shell 命令(带超时保护和命令分类)。返回结果中会标注命令类型(只读/搜索/写入)。')
191
432
  .keyword('执行', '运行', '命令', '终端', 'shell', 'bash')
192
433
  .tag('shell', 'exec')
193
434
  .kind('shell')
@@ -202,33 +443,47 @@ export function createBuiltinTools(options) {
202
443
  const safety = checkBashCommandSafety(cmd);
203
444
  if (!safety.safe)
204
445
  return `Error: ${safety.reason}`;
446
+ // 命令读写分类
447
+ const classification = classifyBashCommand(cmd);
205
448
  const { stdout, stderr } = await execAsync(cmd, {
206
449
  cwd: args.cwd || process.cwd(),
207
450
  timeout,
208
451
  maxBuffer: 1024 * 1024,
209
452
  });
210
453
  let result = '';
454
+ const tag = classification.isReadOnly
455
+ ? (classification.isSearch ? '[搜索]' : classification.isList ? '[列出]' : '[只读]')
456
+ : '[执行]';
211
457
  if (stdout.trim())
212
458
  result += `STDOUT:\n${stdout.trim()}`;
213
459
  if (stderr.trim())
214
460
  result += `${result ? '\n' : ''}STDERR:\n${stderr.trim()}`;
215
- return result || '(no output)';
461
+ return `${tag} ${result || '(no output)'}`;
216
462
  }
217
463
  catch (e) {
218
464
  const err = e;
219
465
  return `Error (exit ${err.code || '?'}): ${errMsg(e)}\nSTDOUT:\n${err.stdout || ''}\nSTDERR:\n${err.stderr || ''}`;
220
466
  }
221
467
  }));
222
- // ── web_search(搜索网页,返回标题、URL、摘要) ──
468
+ // ── web_search(搜索网页,返回标题、URL、摘要 + 域名过滤 + 次数限制) ──
469
+ let searchCount = 0;
470
+ const MAX_SEARCH_COUNT = 20; // 单次会话搜索次数上限
223
471
  tools.push(new ZhinTool('web_search')
224
- .desc('在互联网上搜索,返回匹配的标题、URL 和摘要片段。用于查资料、找网页。')
472
+ .desc('在互联网上搜索,返回匹配的标题、URL 和摘要片段。用于查资料、找网页。支持域名过滤。')
225
473
  .keyword('搜索', '网上搜', '网页搜索', '搜索引擎', 'search', 'google', '百度', '查询', '搜一下')
226
474
  .tag('web', 'search')
227
475
  .kind('web')
228
476
  .param('query', { type: 'string', description: '搜索关键词或完整查询语句' }, true)
229
477
  .param('limit', { type: 'number', description: '返回结果数量(默认 5,建议 1–10)' })
478
+ .param('allowed_domains', { type: 'array', description: '仅保留这些域名的结果(可选,如 ["github.com", "stackoverflow.com"])' })
479
+ .param('blocked_domains', { type: 'array', description: '排除这些域名的结果(可选)' })
230
480
  .execute(async (args) => {
231
481
  try {
482
+ // 搜索次数限制
483
+ searchCount++;
484
+ if (searchCount > MAX_SEARCH_COUNT) {
485
+ return `Error: 搜索次数已达上限 (${MAX_SEARCH_COUNT})。请使用已获取的信息回答。`;
486
+ }
232
487
  const limit = args.limit ?? 5;
233
488
  const url = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(args.query)}`;
234
489
  const res = await fetch(url, {
@@ -266,37 +521,97 @@ export function createBuiltinTools(options) {
266
521
  results.push({ title, url: href, snippet });
267
522
  }
268
523
  }
269
- if (results.length === 0)
524
+ // 域名过滤
525
+ let filtered = results;
526
+ if (args.allowed_domains?.length) {
527
+ const allowed = new Set(args.allowed_domains.map(d => d.toLowerCase()));
528
+ filtered = filtered.filter(r => {
529
+ try {
530
+ return allowed.has(new URL(r.url).hostname.toLowerCase());
531
+ }
532
+ catch {
533
+ return false;
534
+ }
535
+ });
536
+ }
537
+ if (args.blocked_domains?.length) {
538
+ const blocked = new Set(args.blocked_domains.map(d => d.toLowerCase()));
539
+ filtered = filtered.filter(r => {
540
+ try {
541
+ return !blocked.has(new URL(r.url).hostname.toLowerCase());
542
+ }
543
+ catch {
544
+ return true;
545
+ }
546
+ });
547
+ }
548
+ if (filtered.length === 0)
270
549
  return 'No results found.';
271
- return results.map((r, i) => `${i + 1}. ${r.title}\n URL: ${r.url}\n ${r.snippet}`).join('\n\n');
550
+ 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');
272
551
  }
273
552
  catch (e) {
274
553
  return `Error: ${errMsg(e)}`;
275
554
  }
276
555
  }));
277
- // ── web_fetch(抓取 URL 并提取正文) ──
556
+ // ── web_fetch(抓取 URL 并提取正文 + SSRF 防护 + 改进的内容提取) ──
278
557
  tools.push(new ZhinTool('web_fetch')
279
- .desc('抓取指定 URL 的网页内容并提取正文(去除广告等),返回可读文本。用于读文章、获取网页内容。')
558
+ .desc('抓取指定 URL 的网页内容并提取正文(去除广告、脚本等),返回可读文本。仅支持 http/https 协议。')
280
559
  .keyword('抓取网页', '打开链接', '获取网页', '读网页', 'fetch', 'url', '链接内容', '网页内容')
281
560
  .tag('web', 'fetch')
282
561
  .kind('web')
283
562
  .param('url', { type: 'string', description: '要抓取的完整 URL(需 http 或 https)' }, true)
563
+ .param('max_length', { type: 'number', description: '最大返回字符数(默认 20480)' })
284
564
  .execute(async (args) => {
285
565
  try {
566
+ // SSRF 防护:仅允许 http/https 协议
567
+ let parsedUrl;
568
+ try {
569
+ parsedUrl = new URL(args.url);
570
+ }
571
+ catch {
572
+ return `Error: 无效的 URL 格式`;
573
+ }
574
+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
575
+ return `Error: 仅支持 http/https 协议,拒绝 ${parsedUrl.protocol}`;
576
+ }
577
+ // 阻止内网地址(SSRF 关键防护)
578
+ const hostname = parsedUrl.hostname.toLowerCase();
579
+ if (hostname === 'localhost' ||
580
+ hostname === '127.0.0.1' ||
581
+ hostname === '::1' ||
582
+ hostname === '0.0.0.0' ||
583
+ hostname.endsWith('.local') ||
584
+ hostname.startsWith('10.') ||
585
+ hostname.startsWith('192.168.') ||
586
+ /^172\.(1[6-9]|2\d|3[01])\./.test(hostname)) {
587
+ return `Error: 禁止访问内网地址 ${hostname}(SSRF 防护)`;
588
+ }
286
589
  const response = await fetch(args.url, {
287
590
  headers: { 'User-Agent': 'Mozilla/5.0 (compatible; ZhinBot/1.0)' },
288
591
  signal: AbortSignal.timeout(15000),
592
+ redirect: 'follow',
289
593
  });
290
594
  if (!response.ok)
291
595
  return `HTTP ${response.status}: ${response.statusText}`;
292
596
  const html = await response.text();
597
+ // 改进的内容提取:去除脚本、样式、导航、页脚、表单等
293
598
  const text = html
294
599
  .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
295
600
  .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
601
+ .replace(/<nav[^>]*>[\s\S]*?<\/nav>/gi, '')
602
+ .replace(/<footer[^>]*>[\s\S]*?<\/footer>/gi, '')
603
+ .replace(/<header[^>]*>[\s\S]*?<\/header>/gi, ' ')
604
+ .replace(/<form[^>]*>[\s\S]*?<\/form>/gi, '')
605
+ .replace(/<!--[\s\S]*?-->/g, '')
296
606
  .replace(/<[^>]+>/g, ' ')
607
+ .replace(/&nbsp;/gi, ' ')
608
+ .replace(/&amp;/g, '&')
609
+ .replace(/&lt;/g, '<')
610
+ .replace(/&gt;/g, '>')
611
+ .replace(/&quot;/g, '"')
297
612
  .replace(/\s+/g, ' ')
298
613
  .trim();
299
- const maxLen = 20 * 1024;
614
+ const maxLen = args.max_length ?? 20 * 1024;
300
615
  return text.length > maxLen ? text.slice(0, maxLen) + '\n...(truncated)' : text;
301
616
  }
302
617
  catch (e) {
@@ -469,6 +784,98 @@ export function createBuiltinTools(options) {
469
784
  return `Error: ${errMsg(e)}`;
470
785
  }
471
786
  }));
787
+ // ── ask_user(基于 Prompt 类的用户确认/提问工具) ──
788
+ // 安全策略:在群聊中 ask_user 只向 owner 私聊确认,防止非 owner 用户操控安全敏感决策
789
+ tools.push(new ZhinTool('ask_user')
790
+ .desc('向 Bot Owner 发送问题并等待回复。用于需要确认、补充信息或做出选择时。在群聊中始终通过私聊向 Owner 确认,确保安全性。')
791
+ .keyword('询问', '确认', '提问', '用户输入', 'ask', 'confirm', 'prompt', '选择', '请问')
792
+ .tag('interaction', 'prompt')
793
+ .kind('interaction')
794
+ .param('question', { type: 'string', description: '要向 Owner 提出的问题文本' }, true)
795
+ .param('type', { type: 'string', description: '问题类型: text(文本输入)、number(数字输入)、confirm(是/否确认)、pick(选项选择)。默认 text' })
796
+ .param('options', { type: 'array', description: '选项列表(type=pick 时必填),每项为字符串,如 ["选项A","选项B","选项C"]' })
797
+ .param('default_value', { type: 'string', description: 'Owner 超时未回复时使用的默认值' })
798
+ .param('timeout', { type: 'number', description: '等待 Owner 回复的超时时间(秒),默认 120' })
799
+ .execute(async (args, context) => {
800
+ if (!context?.message) {
801
+ return 'Error: 当前上下文没有消息来源,无法向 Owner 提问。请改为在回复中直接询问。';
802
+ }
803
+ if (!pluginRef) {
804
+ return 'Error: 插件实例不可用,无法创建交互式提问。请改为在回复中直接询问。';
805
+ }
806
+ const timeoutMs = (args.timeout ?? 120) * 1000;
807
+ const questionType = args.type || 'text';
808
+ // 从 adapter 的 bot 配置中查找 owner
809
+ const platform = context.platform;
810
+ const botId = context.botId;
811
+ const adapter = pluginRef.inject(platform);
812
+ const bot = adapter?.bots?.get(botId);
813
+ const botOwner = bot?.$config?.owner;
814
+ const isPrivateOwner = context.scope === 'private'
815
+ && botOwner != null && String(context.senderId) === String(botOwner);
816
+ // ── 私聊 + 发送者是 Owner → 直接用 Prompt(原有行为) ──
817
+ if (isPrivateOwner) {
818
+ return askViaPrompt(pluginRef, context.message, args, questionType, timeoutMs);
819
+ }
820
+ // ── 非私聊 Owner → 必须通过私聊向 Owner 确认 ──
821
+ if (!botOwner) {
822
+ return 'Error: 当前 Bot 未配置 owner,无法进行安全确认。请在 bots 配置中设置 owner 字段。';
823
+ }
824
+ if (!adapter || typeof adapter.sendMessage !== 'function') {
825
+ return `Error: 无法获取适配器 ${platform},无法向 Owner 发送私聊确认。`;
826
+ }
827
+ // 构建发送给 Owner 的问题文本(包含来源上下文)
828
+ const sourceInfo = context.scope !== 'private'
829
+ ? `来源: ${context.scope}(${context.sceneId}) 用户: ${context.senderId}`
830
+ : `来源: 私聊 用户: ${context.senderId}`;
831
+ let questionText = `🔐 AI 安全确认\n${sourceInfo}\n\n${args.question}`;
832
+ if (questionType === 'confirm') {
833
+ questionText += '\n输入"yes"以确认';
834
+ }
835
+ else if (questionType === 'pick' && args.options?.length) {
836
+ questionText += '\n' + args.options.map((o, i) => `${i + 1}.${o}`).join('\n');
837
+ }
838
+ else if (questionType === 'number') {
839
+ questionText += '\n(请输入数字)';
840
+ }
841
+ try {
842
+ await adapter.sendMessage({
843
+ context: platform,
844
+ bot: botId,
845
+ id: botOwner,
846
+ type: 'private',
847
+ content: questionText,
848
+ });
849
+ }
850
+ catch (e) {
851
+ return `Error: 无法向 Owner 发送私聊消息: ${errMsg(e)}`;
852
+ }
853
+ // 注册一次性中间件等待 Owner 私聊回复
854
+ return new Promise((resolve) => {
855
+ const middleware = async (message, next) => {
856
+ if (message.$channel?.type !== 'private')
857
+ return next();
858
+ if (String(message.$sender.id) !== String(botOwner))
859
+ return next();
860
+ if (String(message.$bot) !== String(botId))
861
+ return next();
862
+ dispose();
863
+ clearTimeout(timer);
864
+ const raw = message.$raw;
865
+ resolve(formatOwnerResponse(raw, questionType, args));
866
+ };
867
+ const dispose = pluginRef.addMiddleware(middleware);
868
+ const timer = setTimeout(() => {
869
+ dispose();
870
+ if (args.default_value != null) {
871
+ resolve(String(args.default_value));
872
+ }
873
+ else {
874
+ resolve('Owner 未在规定时间内响应,操作已取消。');
875
+ }
876
+ }, timeoutMs);
877
+ });
878
+ }));
472
879
  return tools;
473
880
  }
474
881
  //# sourceMappingURL=builtin-tools.js.map