@zhin.js/agent 0.1.0 → 0.1.2

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 (114) hide show
  1. package/lib/cron-engine.d.ts +16 -1
  2. package/lib/cron-engine.d.ts.map +1 -1
  3. package/lib/cron-engine.js +47 -13
  4. package/lib/cron-engine.js.map +1 -1
  5. package/lib/discover-skills.d.ts +3 -1
  6. package/lib/discover-skills.d.ts.map +1 -1
  7. package/lib/discover-skills.js +7 -9
  8. package/lib/discover-skills.js.map +1 -1
  9. package/lib/discover-tools.d.ts +1 -6
  10. package/lib/discover-tools.d.ts.map +1 -1
  11. package/lib/discover-tools.js +2 -6
  12. package/lib/discover-tools.js.map +1 -1
  13. package/lib/index.d.ts +2 -4
  14. package/lib/index.d.ts.map +1 -1
  15. package/lib/index.js +1 -2
  16. package/lib/index.js.map +1 -1
  17. package/lib/init/create-zhin-agent.d.ts.map +1 -1
  18. package/lib/init/create-zhin-agent.js +31 -20
  19. package/lib/init/create-zhin-agent.js.map +1 -1
  20. package/lib/init/register-ai-trigger.d.ts.map +1 -1
  21. package/lib/init/register-ai-trigger.js +10 -3
  22. package/lib/init/register-ai-trigger.js.map +1 -1
  23. package/lib/init/register-builtin-tools.d.ts.map +1 -1
  24. package/lib/init/register-builtin-tools.js +46 -14
  25. package/lib/init/register-builtin-tools.js.map +1 -1
  26. package/lib/init/register-db-models.d.ts.map +1 -1
  27. package/lib/init/register-db-models.js +1 -3
  28. package/lib/init/register-db-models.js.map +1 -1
  29. package/lib/init/register-db-upgrade.d.ts.map +1 -1
  30. package/lib/init/register-db-upgrade.js +1 -8
  31. package/lib/init/register-db-upgrade.js.map +1 -1
  32. package/lib/init/register-management-tools.d.ts.map +1 -1
  33. package/lib/init/register-management-tools.js +33 -20
  34. package/lib/init/register-management-tools.js.map +1 -1
  35. package/lib/service.d.ts.map +1 -1
  36. package/lib/service.js +0 -8
  37. package/lib/service.js.map +1 -1
  38. package/lib/zhin-agent/builtin-tools.d.ts +0 -2
  39. package/lib/zhin-agent/builtin-tools.d.ts.map +1 -1
  40. package/lib/zhin-agent/builtin-tools.js +0 -55
  41. package/lib/zhin-agent/builtin-tools.js.map +1 -1
  42. package/lib/zhin-agent/config.d.ts +2 -1
  43. package/lib/zhin-agent/config.d.ts.map +1 -1
  44. package/lib/zhin-agent/config.js +1 -1
  45. package/lib/zhin-agent/config.js.map +1 -1
  46. package/lib/zhin-agent/index.d.ts +1 -6
  47. package/lib/zhin-agent/index.d.ts.map +1 -1
  48. package/lib/zhin-agent/index.js +26 -34
  49. package/lib/zhin-agent/index.js.map +1 -1
  50. package/lib/zhin-agent/prompt.d.ts.map +1 -1
  51. package/lib/zhin-agent/prompt.js +31 -76
  52. package/lib/zhin-agent/prompt.js.map +1 -1
  53. package/lib/zhin-agent/tool-collector.d.ts.map +1 -1
  54. package/lib/zhin-agent/tool-collector.js +7 -7
  55. package/lib/zhin-agent/tool-collector.js.map +1 -1
  56. package/package.json +7 -4
  57. package/CHANGELOG.md +0 -190
  58. package/lib/follow-up.d.ts +0 -131
  59. package/lib/follow-up.d.ts.map +0 -1
  60. package/lib/follow-up.js +0 -265
  61. package/lib/follow-up.js.map +0 -1
  62. package/src/agent.ts +0 -6
  63. package/src/bootstrap.ts +0 -309
  64. package/src/builtin-tools.ts +0 -958
  65. package/src/compaction.ts +0 -28
  66. package/src/context-manager.ts +0 -15
  67. package/src/conversation-memory.ts +0 -5
  68. package/src/cron-engine.ts +0 -338
  69. package/src/discover-agents.ts +0 -138
  70. package/src/discover-skills.ts +0 -325
  71. package/src/discover-tools.ts +0 -302
  72. package/src/discovery-utils.ts +0 -96
  73. package/src/file-policy.ts +0 -333
  74. package/src/follow-up.ts +0 -357
  75. package/src/hooks.ts +0 -223
  76. package/src/index.ts +0 -183
  77. package/src/init/create-zhin-agent.ts +0 -161
  78. package/src/init/register-ai-service.ts +0 -53
  79. package/src/init/register-ai-trigger.ts +0 -253
  80. package/src/init/register-builtin-tools.ts +0 -308
  81. package/src/init/register-db-models.ts +0 -31
  82. package/src/init/register-db-upgrade.ts +0 -77
  83. package/src/init/register-management-tools.ts +0 -71
  84. package/src/init/register-message-recorder.ts +0 -31
  85. package/src/init/register-tool-service.ts +0 -9
  86. package/src/init/shared-refs.ts +0 -20
  87. package/src/init/types.ts +0 -18
  88. package/src/init.ts +0 -50
  89. package/src/output.ts +0 -15
  90. package/src/rate-limiter.ts +0 -5
  91. package/src/service.ts +0 -228
  92. package/src/session.ts +0 -13
  93. package/src/storage.ts +0 -9
  94. package/src/subagent.ts +0 -209
  95. package/src/tone-detector.ts +0 -5
  96. package/src/tools.ts +0 -214
  97. package/src/user-profile.ts +0 -182
  98. package/src/zhin-agent/builtin-tools.ts +0 -247
  99. package/src/zhin-agent/config.ts +0 -124
  100. package/src/zhin-agent/exec-policy.ts +0 -285
  101. package/src/zhin-agent/index.ts +0 -633
  102. package/src/zhin-agent/prompt.ts +0 -305
  103. package/src/zhin-agent/tool-collector.ts +0 -249
  104. package/tests/ai/follow-up.test.ts +0 -175
  105. package/tests/ai/integration.test.ts +0 -582
  106. package/tests/ai/multimodal.test.ts +0 -106
  107. package/tests/ai/setup.ts +0 -186
  108. package/tests/ai/subagent.test.ts +0 -270
  109. package/tests/ai/tools-builtin.test.ts +0 -310
  110. package/tests/ai/user-profile.test.ts +0 -73
  111. package/tests/ai/zhin-agent.test.ts +0 -306
  112. package/tests/exec-policy.test.ts +0 -355
  113. package/tests/file-policy.test.ts +0 -405
  114. package/tsconfig.json +0 -22
@@ -1,958 +0,0 @@
1
- /**
2
- * AI 内置系统工具
3
- *
4
- * 文件工具: read_file, write_file, edit_file, list_dir, glob, grep
5
- * Shell: bash
6
- * 网络: web_search, web_fetch
7
- * 计划: todo_read, todo_write
8
- * 记忆: read_memory, write_memory (AGENTS.md)
9
- * 技能: activate_skill, install_skill
10
- * 交互: ask_user(基于 Prompt 类的用户确认/提问工具)
11
- *
12
- * 发现逻辑已拆分到 discover-skills.ts / discover-agents.ts / discover-tools.ts
13
- */
14
-
15
- import * as fs from 'fs';
16
- import * as path from 'path';
17
- import { exec } from 'child_process';
18
- import { promisify } from 'util';
19
- import { Logger, Prompt, Adapter, type Plugin, type PropertySchema, type MessageMiddleware, type SendOptions } from '@zhin.js/core';
20
- import { ZhinTool } from '@zhin.js/core';
21
- import {
22
- assertFileAccess, checkBashCommandSafety, shellEscape,
23
- isBlockedDevicePath, MAX_READ_FILE_SIZE, MAX_EDIT_FILE_SIZE,
24
- classifyBashCommand, getFileMtime, isFileStale,
25
- } from './file-policy.js';
26
- import {
27
- errMsg, expandHome, getDataDir, mergeSkillDirsWithResolver, nodeErrToFileMessage,
28
- } from './discovery-utils.js';
29
- import { checkSkillDeps, extractSkillInstructions } from './discover-skills.js';
30
-
31
- const execAsync = promisify(exec);
32
- const logger = new Logger(null, 'builtin-tools');
33
-
34
- // ── 引号归一化 + 模糊匹配(参考 Claude Code FileEditTool/utils.ts) ──
35
-
36
- /** 将弯引号归一化为直引号 */
37
- function normalizeQuotes(str: string): string {
38
- return str
39
- .replace(/\u2018/g, "'") // '
40
- .replace(/\u2019/g, "'") // '
41
- .replace(/\u201C/g, '"') // "
42
- .replace(/\u201D/g, '"'); // "
43
- }
44
-
45
- interface FuzzyMatchResult {
46
- /** 文件中实际匹配到的字符串 */
47
- actual: string;
48
- /** 匹配次数 */
49
- count: number;
50
- /** 是否通过引号归一化匹配 */
51
- wasNormalized: boolean;
52
- }
53
-
54
- /**
55
- * 在文件内容中查找字符串,支持精确匹配和引号归一化模糊匹配。
56
- * 参考 Claude Code `findActualString`。
57
- */
58
- function findActualStringInFile(fileContent: string, searchString: string): FuzzyMatchResult | null {
59
- // 精确匹配
60
- const exactCount = fileContent.split(searchString).length - 1;
61
- if (exactCount > 0) {
62
- return { actual: searchString, count: exactCount, wasNormalized: false };
63
- }
64
-
65
- // 引号归一化匹配
66
- const normalizedSearch = normalizeQuotes(searchString);
67
- const normalizedFile = normalizeQuotes(fileContent);
68
- const idx = normalizedFile.indexOf(normalizedSearch);
69
- if (idx !== -1) {
70
- // 提取文件中实际的字符串(保留原始弯引号)
71
- const actual = fileContent.substring(idx, idx + searchString.length);
72
- const normalizedCount = normalizedFile.split(normalizedSearch).length - 1;
73
- return { actual, count: normalizedCount, wasNormalized: true };
74
- }
75
-
76
- return null;
77
- }
78
-
79
- /**
80
- * 将 new_string 中的直引号替换为文件中原始的弯引号风格。
81
- * 参考 Claude Code `preserveQuoteStyle`。
82
- */
83
- function preserveQuoteStyleInEdit(oldString: string, actualOldString: string, newString: string): string {
84
- if (oldString === actualOldString) return newString;
85
-
86
- const hasDouble = actualOldString.includes('\u201C') || actualOldString.includes('\u201D');
87
- const hasSingle = actualOldString.includes('\u2018') || actualOldString.includes('\u2019');
88
- if (!hasDouble && !hasSingle) return newString;
89
-
90
- let result = newString;
91
- if (hasDouble) {
92
- // 简单启发式:前面是空白/行首时用左引号,否则右引号
93
- const chars = [...result];
94
- const out: string[] = [];
95
- for (let i = 0; i < chars.length; i++) {
96
- if (chars[i] === '"') {
97
- const prev = i > 0 ? chars[i - 1] : ' ';
98
- const isOpening = /[\s(\[{]/.test(prev) || i === 0;
99
- out.push(isOpening ? '\u201C' : '\u201D');
100
- } else {
101
- out.push(chars[i]);
102
- }
103
- }
104
- result = out.join('');
105
- }
106
- if (hasSingle) {
107
- const chars = [...result];
108
- const out: string[] = [];
109
- for (let i = 0; i < chars.length; i++) {
110
- if (chars[i] === "'") {
111
- const prev = i > 0 ? chars[i - 1] : ' ';
112
- const next = i < chars.length - 1 ? chars[i + 1] : ' ';
113
- // 两个字母之间是缩写,用右引号
114
- if (/\p{L}/u.test(prev) && /\p{L}/u.test(next)) {
115
- out.push('\u2019');
116
- } else {
117
- const isOpening = /[\s(\[{]/.test(prev) || i === 0;
118
- out.push(isOpening ? '\u2018' : '\u2019');
119
- }
120
- } else {
121
- out.push(chars[i]);
122
- }
123
- }
124
- result = out.join('');
125
- }
126
- return result;
127
- }
128
-
129
- // ── 图片格式检测(参考 Claude Code FileReadTool imageResizer) ──
130
-
131
- /** 支持的图片扩展名 */
132
- const IMAGE_EXTENSIONS: ReadonlySet<string> = new Set([
133
- '.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.svg', '.ico',
134
- ]);
135
-
136
- function isImageFile(filePath: string): boolean {
137
- return IMAGE_EXTENSIONS.has(path.extname(filePath).toLowerCase());
138
- }
139
-
140
- // ============================================================================
141
- // ask_user 辅助函数
142
- // ============================================================================
143
-
144
- /**
145
- * 私聊 Owner 场景:使用 Prompt 类直接交互(原有行为)
146
- */
147
- async function askViaPrompt(
148
- plugin: Plugin,
149
- message: any,
150
- args: Record<string, any>,
151
- questionType: string,
152
- timeoutMs: number,
153
- ): Promise<string> {
154
- const prompt = new Prompt(plugin, message);
155
- try {
156
- switch (questionType) {
157
- case 'number': {
158
- const defaultNum = args.default_value != null ? Number(args.default_value) : undefined;
159
- const result = await prompt.number(args.question, timeoutMs, defaultNum, '输入超时,已取消');
160
- return String(result);
161
- }
162
- case 'confirm': {
163
- const result = await prompt.confirm(args.question, 'yes', timeoutMs, false, '确认超时,已取消');
164
- return result ? 'yes' : 'no';
165
- }
166
- case 'pick': {
167
- if (!args.options?.length) {
168
- return 'Error: type=pick 时必须提供 options 选项列表';
169
- }
170
- const pickOptions = (args.options as string[]).map((o: string) => ({ label: o, value: o }));
171
- const result = await prompt.pick(args.question, {
172
- type: 'text' as const,
173
- options: pickOptions,
174
- timeout: timeoutMs,
175
- }, '选择超时,已取消');
176
- return String(result);
177
- }
178
- case 'text':
179
- default: {
180
- const result = await prompt.text(args.question, timeoutMs, args.default_value || '', '输入超时,已取消');
181
- return result;
182
- }
183
- }
184
- } catch (e: unknown) {
185
- return `Owner 未响应或输入错误: ${errMsg(e)}`;
186
- }
187
- }
188
-
189
- /**
190
- * 将 Owner 私聊回复格式化为对应类型的结果
191
- */
192
- function formatOwnerResponse(raw: string, questionType: string, args: Record<string, any>): string {
193
- switch (questionType) {
194
- case 'confirm':
195
- return raw.trim().toLowerCase() === 'yes' ? 'yes' : 'no';
196
- case 'number':
197
- return String(Number(raw) || 0);
198
- case 'pick': {
199
- const idx = Number(raw.trim());
200
- const options = (args.options as string[]) || [];
201
- if (idx >= 1 && idx <= options.length) return options[idx - 1];
202
- return raw;
203
- }
204
- case 'text':
205
- default:
206
- return raw;
207
- }
208
- }
209
-
210
- // ============================================================================
211
- // 工具工厂函数
212
- // ============================================================================
213
-
214
- export interface BuiltinToolsOptions {
215
- /** 插件实例,用于 ask_user 工具创建 Prompt 交互 */
216
- plugin?: Plugin;
217
- /** Max chars for skill instruction extraction (model-size-aware) */
218
- skillInstructionMaxChars?: number;
219
- /**
220
- * 返回额外技能根目录(每个根下为 `<skillName>/SKILL.md`),通常为已加载插件的 `.../skills`
221
- */
222
- pluginSkillRootsResolver?: () => string[];
223
- /**
224
- * 按名称查找 SkillFeature 中已注册技能的 filePath
225
- * 返回 SKILL.md 的绝对路径,或 undefined 表示未找到
226
- */
227
- skillFileLookup?: (name: string) => string | undefined;
228
- }
229
-
230
- /**
231
- * 创建所有内置系统工具
232
- */
233
- export function createBuiltinTools(options?: BuiltinToolsOptions): ZhinTool[] {
234
- const DATA_DIR = getDataDir();
235
- const skillMaxChars = options?.skillInstructionMaxChars ?? 4000;
236
- const skillDirList = () => mergeSkillDirsWithResolver(options?.pluginSkillRootsResolver);
237
- const skillFileLookup = options?.skillFileLookup;
238
- const pluginRef = options?.plugin;
239
-
240
- const tools: ZhinTool[] = [];
241
-
242
- // ── read_file(清晰描述 + 强关键词 + 图片检测 + 安全防护) ──
243
- tools.push(
244
- new ZhinTool('read_file')
245
- .desc('读取指定路径的文件内容。用于查看、打开或读取任意文本文件。图片文件返回 Base64 数据。')
246
- .keyword('读文件', '读取文件', '查看文件', '打开文件', '文件内容', 'read file', 'read', 'cat', '查看', '打开')
247
- .tag('file', 'read')
248
- .kind('file')
249
- .param('file_path', { type: 'string', description: '要读取的文件路径(绝对路径或相对项目根目录)' }, true)
250
- .param('offset', { type: 'number', description: '起始行号(0-based,可选,默认从第 1 行开始)' })
251
- .param('limit', { type: 'number', description: '最多读取行数(可选,默认全部)' })
252
- .execute(async (args) => {
253
- try {
254
- const fp = expandHome(args.file_path);
255
- // 设备路径拦截(参考 Claude Code BLOCKED_DEVICE_PATHS)
256
- if (isBlockedDevicePath(fp)) {
257
- return `Error: 禁止读取设备文件 ${fp}(会导致进程挂起或注入攻击)`;
258
- }
259
- assertFileAccess(fp);
260
- const stat = await fs.promises.stat(fp);
261
- // 文件大小限制(参考 Claude Code MAX_EDIT_FILE_SIZE)
262
- if (stat.size > MAX_READ_FILE_SIZE) {
263
- return `Error: 文件过大 (${(stat.size / 1024 / 1024).toFixed(1)} MiB),超过 ${MAX_READ_FILE_SIZE / 1024 / 1024} MiB 限制。请使用 offset/limit 分段读取。`;
264
- }
265
-
266
- // 图片文件检测(参考 Claude Code FileReadTool 的图片处理)
267
- if (isImageFile(fp)) {
268
- const buffer = await fs.promises.readFile(fp);
269
- const ext = path.extname(fp).toLowerCase().replace('.', '');
270
- const mimeType = ext === 'jpg' ? 'jpeg' : ext === 'svg' ? 'svg+xml' : ext;
271
- const b64 = buffer.toString('base64');
272
- const sizeKb = (buffer.length / 1024).toFixed(1);
273
- return `[Image: ${path.basename(fp)}, ${sizeKb} KB, type: image/${mimeType}]\ndata:image/${mimeType};base64,${b64.slice(0, 200)}...(total ${b64.length} chars)`;
274
- }
275
-
276
- const content = await fs.promises.readFile(fp, 'utf-8');
277
- const lines = content.split('\n');
278
- const offset = args.offset ?? 0;
279
- const limit = args.limit ?? lines.length;
280
- const sliced = lines.slice(offset, offset + limit);
281
- const numbered = sliced.map((line: string, i: number) => `${offset + i + 1} | ${line}`).join('\n');
282
- return `File: ${fp} (${lines.length} lines, showing ${offset + 1}-${Math.min(offset + limit, lines.length)})\n${numbered}`;
283
- } catch (e: unknown) {
284
- return nodeErrToFileMessage(e, args.file_path, 'read');
285
- }
286
- }),
287
- );
288
-
289
- // ── write_file ──
290
- tools.push(
291
- new ZhinTool('write_file')
292
- .desc('向指定路径写入内容,创建或覆盖文件;若目录不存在会自动创建。')
293
- .keyword('写文件', '写入文件', '创建文件', '保存文件', 'write file', 'write', '保存', '创建')
294
- .tag('file', 'write')
295
- .kind('file')
296
- .param('file_path', { type: 'string', description: '要写入的文件路径' }, true)
297
- .param('content', { type: 'string', description: '要写入的完整内容' }, true)
298
- .execute(async (args) => {
299
- try {
300
- const fp = expandHome(args.file_path);
301
- assertFileAccess(fp);
302
- await fs.promises.mkdir(path.dirname(fp), { recursive: true });
303
- await fs.promises.writeFile(fp, args.content, 'utf-8');
304
- return `✅ Wrote ${Buffer.byteLength(args.content)} bytes to ${fp}`;
305
- } catch (e: unknown) {
306
- return nodeErrToFileMessage(e, args.file_path, 'write');
307
- }
308
- }),
309
- );
310
-
311
- // ── edit_file(支持精确匹配 + 引号归一化模糊匹配)──
312
- tools.push(
313
- new ZhinTool('edit_file')
314
- .desc('在文件中查找并替换一段文本。old_string 必须在文件中精确存在且唯一;建议包含完整行或足够上下文以避免重复匹配。支持弯引号/直引号自动归一化。')
315
- .keyword('编辑文件', '修改文件', '替换内容', '查找替换', 'edit file', 'edit', '修改', '替换')
316
- .tag('file', 'edit')
317
- .kind('file')
318
- .param('file_path', { type: 'string', description: '要编辑的文件路径' }, true)
319
- .param('old_string', { type: 'string', description: '文件中要替换的原文(必须与文件内容完全一致)' }, true)
320
- .param('new_string', { type: 'string', description: '替换后的新文本' }, true)
321
- .execute(async (args) => {
322
- try {
323
- const fp = expandHome(args.file_path);
324
- assertFileAccess(fp);
325
- // 文件大小限制
326
- const stat = await fs.promises.stat(fp);
327
- if (stat.size > MAX_EDIT_FILE_SIZE) {
328
- return `Error: 文件过大 (${(stat.size / 1024 / 1024).toFixed(1)} MiB),超过 ${MAX_EDIT_FILE_SIZE / 1024 / 1024} MiB 限制。`;
329
- }
330
- // 记录 mtime 用于防并发覆写
331
- const mtimeBefore = stat.mtimeMs;
332
- const content = await fs.promises.readFile(fp, 'utf-8');
333
-
334
- // 精确匹配 → 引号归一化模糊匹配
335
- const matchResult = findActualStringInFile(content, args.old_string);
336
- if (!matchResult) return `Error: old_string not found in file. Make sure it matches exactly (also tried quote normalization).`;
337
- if (matchResult.count > 1) return `Warning: old_string appears ${matchResult.count} times. Please provide more context to make it unique.`;
338
-
339
- // 如果通过引号归一化匹配,保持文件的引号风格
340
- const effectiveNew = matchResult.wasNormalized
341
- ? preserveQuoteStyleInEdit(args.old_string, matchResult.actual, args.new_string)
342
- : args.new_string;
343
-
344
- const newContent = content.replace(matchResult.actual, effectiveNew);
345
-
346
- // 写入前再检查 mtime 防止并发修改
347
- const currentStat = await fs.promises.stat(fp);
348
- if (isFileStale(mtimeBefore, currentStat.mtimeMs)) {
349
- return `Error: 文件 ${fp} 在读取后被外部修改。请重新读取文件后再编辑,避免覆盖他人的修改。`;
350
- }
351
- await fs.promises.writeFile(fp, newContent, 'utf-8');
352
-
353
- const oldLines = args.old_string.split('\n');
354
- const newLines = args.new_string.split('\n');
355
- return `✅ Edited ${fp}\n--- before ---\n${oldLines.slice(0, 5).join('\n')}${oldLines.length > 5 ? '\n...' : ''}\n--- after ---\n${newLines.slice(0, 5).join('\n')}${newLines.length > 5 ? '\n...' : ''}`;
356
- } catch (e: unknown) {
357
- return nodeErrToFileMessage(e, args.file_path, 'edit');
358
- }
359
- }),
360
- );
361
-
362
- // ── list_dir(列出目录内容,便于 AI 匹配「列表」「目录」「ls」) ──
363
- tools.push(
364
- new ZhinTool('list_dir')
365
- .desc('列出指定目录下的文件和子目录名称。用于查看目录结构、有哪些文件。')
366
- .keyword('列目录', '列出目录', '目录列表', '查看目录', 'list directory', 'list dir', 'ls', 'dir', '目录内容', '有哪些文件')
367
- .tag('file', 'list')
368
- .kind('file')
369
- .param('path', { type: 'string', description: '要列出的目录路径(绝对或相对项目根目录)' }, true)
370
- .execute(async (args) => {
371
- try {
372
- const dirPath = path.resolve(process.cwd(), expandHome(args.path));
373
- assertFileAccess(dirPath);
374
- const stat = await fs.promises.stat(dirPath);
375
- if (!stat.isDirectory()) {
376
- return `Error: Not a directory: ${args.path}`;
377
- }
378
- const entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
379
- if (entries.length === 0) {
380
- return `Directory ${args.path} is empty`;
381
- }
382
- const lines: string[] = [];
383
- for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
384
- lines.push((e.isDirectory() ? '[DIR] ' : ' ') + e.name);
385
- }
386
- return lines.join('\n');
387
- } catch (e: unknown) {
388
- return nodeErrToFileMessage(e, args.path, 'list');
389
- }
390
- }),
391
- );
392
-
393
- // ── glob ──
394
- tools.push(
395
- new ZhinTool('glob')
396
- .desc('按 glob 模式查找匹配的文件路径(如 **/*.ts)。用于按模式找文件,而非列出目录。')
397
- .keyword('glob', '查找文件', '按模式找文件', 'find', '匹配文件')
398
- .tag('file', 'search')
399
- .kind('file')
400
- .param('pattern', { type: 'string', description: 'Glob 模式(如 **/*.ts)' }, true)
401
- .param('cwd', { type: 'string', description: '工作目录(默认项目根目录)' })
402
- .execute(async (args) => {
403
- try {
404
- const cwd = args.cwd || process.cwd();
405
- assertFileAccess(cwd);
406
- // 安全转义 glob pattern 防止命令注入
407
- const safePattern = shellEscape(args.pattern);
408
- const { stdout } = await execAsync(
409
- `find . -path ./${safePattern} -type f 2>/dev/null | head -100`,
410
- { cwd },
411
- );
412
- const files = stdout.trim().split('\n').filter(Boolean);
413
- return files.length === 0
414
- ? `No files matching '${args.pattern}'`
415
- : `Found ${files.length} files:\n${files.join('\n')}`;
416
- } catch (e: unknown) {
417
- return `Error: ${errMsg(e)}`;
418
- }
419
- }),
420
- );
421
-
422
- // ── grep(支持上下文行、大小写、多行、ripgrep 自动检测) ──
423
- tools.push(
424
- new ZhinTool('grep')
425
- .desc('按正则搜索文件内容,返回匹配行和行号。优先使用 ripgrep (rg),回退到 grep。')
426
- .keyword('搜索', '查找内容', 'grep', '正则', 'rg', 'ripgrep')
427
- .tag('search', 'regex')
428
- .kind('file')
429
- .param('pattern', { type: 'string', description: '正则表达式' }, true)
430
- .param('path', { type: 'string', description: '搜索路径(默认 .)' })
431
- .param('include', { type: 'string', description: '文件类型过滤(如 *.ts)' })
432
- .param('context', { type: 'number', description: '匹配行上下文行数(-C 参数)' })
433
- .param('before', { type: 'number', description: '匹配行之前显示行数(-B 参数)' })
434
- .param('after', { type: 'number', description: '匹配行之后显示行数(-A 参数)' })
435
- .param('ignore_case', { type: 'boolean', description: '大小写不敏感搜索(-i 参数)' } as any)
436
- .param('multiline', { type: 'boolean', description: '多行模式,. 匹配换行(仅 ripgrep 支持)' } as any)
437
- .param('limit', { type: 'number', description: '最多返回结果行数(默认 50)' })
438
- .execute(async (args) => {
439
- try {
440
- const searchPath = args.path || '.';
441
- assertFileAccess(path.resolve(process.cwd(), searchPath));
442
- const safePattern = shellEscape(args.pattern);
443
- const safePath = shellEscape(searchPath);
444
- const limit = args.limit ?? 50;
445
-
446
- // 检测 ripgrep 是否可用
447
- let useRipgrep = false;
448
- try {
449
- await execAsync('rg --version', { timeout: 3000 });
450
- useRipgrep = true;
451
- } catch { /* ripgrep 不可用,回退到 grep */ }
452
-
453
- let cmd: string;
454
- if (useRipgrep) {
455
- // ripgrep 命令构建
456
- const rgFlags: string[] = ['-n']; // 行号
457
- if (args.ignore_case) rgFlags.push('-i');
458
- if (args.multiline) rgFlags.push('-U', '--multiline-dotall');
459
- if (args.context) rgFlags.push(`-C${args.context}`);
460
- else {
461
- if (args.before) rgFlags.push(`-B${args.before}`);
462
- if (args.after) rgFlags.push(`-A${args.after}`);
463
- }
464
- if (args.include) rgFlags.push(`--glob=${shellEscape(args.include)}`);
465
- cmd = `rg ${rgFlags.join(' ')} ${safePattern} ${safePath} 2>/dev/null | head -${limit}`;
466
- } else {
467
- // 传统 grep 回退
468
- const grepFlags: string[] = ['-rn'];
469
- if (args.ignore_case) grepFlags.push('-i');
470
- if (args.context) grepFlags.push(`-C${args.context}`);
471
- else {
472
- if (args.before) grepFlags.push(`-B${args.before}`);
473
- if (args.after) grepFlags.push(`-A${args.after}`);
474
- }
475
- const includeFlag = args.include ? `--include=${shellEscape(args.include)}` : '';
476
- cmd = `grep ${grepFlags.join(' ')} ${includeFlag} ${safePattern} ${safePath} 2>/dev/null | head -${limit}`;
477
- }
478
-
479
- const { stdout } = await execAsync(cmd, { cwd: process.cwd() });
480
- const engine = useRipgrep ? '(ripgrep)' : '(grep)';
481
- return stdout.trim()
482
- ? `${engine}\n${stdout.trim()}`
483
- : `No matches for '${args.pattern}' ${engine}`;
484
- } catch (e: unknown) {
485
- const err = e as { code?: number; message?: string };
486
- if (err.code === 1) return `No matches for '${args.pattern}'`;
487
- return `Error: ${errMsg(e)}`;
488
- }
489
- }),
490
- );
491
-
492
- // ── bash(安全检查 + 命令读写分类) ──
493
- tools.push(
494
- new ZhinTool('bash')
495
- .desc('执行 Shell 命令(带超时保护和命令分类)。返回结果中会标注命令类型(只读/搜索/写入)。')
496
- .keyword('执行', '运行', '命令', '终端', 'shell', 'bash')
497
- .tag('shell', 'exec')
498
- .kind('shell')
499
- .param('command', { type: 'string', description: 'Shell 命令' }, true)
500
- .param('cwd', { type: 'string', description: '工作目录' })
501
- .param('timeout', { type: 'number', description: '超时毫秒数(默认 30000)' })
502
- .execute(async (args) => {
503
- try {
504
- const timeout = args.timeout ?? 30000;
505
- const cmd = String(args.command || '');
506
- // 检查命令是否可能泄漏敏感信息
507
- const safety = checkBashCommandSafety(cmd);
508
- if (!safety.safe) return `Error: ${safety.reason}`;
509
- // 命令读写分类
510
- const classification = classifyBashCommand(cmd);
511
- const { stdout, stderr } = await execAsync(cmd, {
512
- cwd: args.cwd || process.cwd(),
513
- timeout,
514
- maxBuffer: 1024 * 1024,
515
- });
516
- let result = '';
517
- const tag = classification.isReadOnly
518
- ? (classification.isSearch ? '[搜索]' : classification.isList ? '[列出]' : '[只读]')
519
- : '[执行]';
520
- if (stdout.trim()) result += `STDOUT:\n${stdout.trim()}`;
521
- if (stderr.trim()) result += `${result ? '\n' : ''}STDERR:\n${stderr.trim()}`;
522
- return `${tag} ${result || '(no output)'}`;
523
- } catch (e: unknown) {
524
- const err = e as { code?: number; message?: string; stdout?: string; stderr?: string };
525
- return `Error (exit ${err.code || '?'}): ${errMsg(e)}\nSTDOUT:\n${err.stdout || ''}\nSTDERR:\n${err.stderr || ''}`;
526
- }
527
- }),
528
- );
529
-
530
- // ── web_search(搜索网页,返回标题、URL、摘要 + 域名过滤 + 次数限制) ──
531
- let searchCount = 0;
532
- const MAX_SEARCH_COUNT = 20; // 单次会话搜索次数上限
533
- tools.push(
534
- new ZhinTool('web_search')
535
- .desc('在互联网上搜索,返回匹配的标题、URL 和摘要片段。用于查资料、找网页。支持域名过滤。')
536
- .keyword('搜索', '网上搜', '网页搜索', '搜索引擎', 'search', 'google', '百度', '查询', '搜一下')
537
- .tag('web', 'search')
538
- .kind('web')
539
- .param('query', { type: 'string', description: '搜索关键词或完整查询语句' }, true)
540
- .param('limit', { type: 'number', description: '返回结果数量(默认 5,建议 1–10)' })
541
- .param('allowed_domains', { type: 'array', description: '仅保留这些域名的结果(可选,如 ["github.com", "stackoverflow.com"])' } as any)
542
- .param('blocked_domains', { type: 'array', description: '排除这些域名的结果(可选)' } as any)
543
- .execute(async (args) => {
544
- try {
545
- // 搜索次数限制
546
- searchCount++;
547
- if (searchCount > MAX_SEARCH_COUNT) {
548
- return `Error: 搜索次数已达上限 (${MAX_SEARCH_COUNT})。请使用已获取的信息回答。`;
549
- }
550
-
551
- const limit = args.limit ?? 5;
552
- const url = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(args.query)}`;
553
- const res = await fetch(url, {
554
- headers: {
555
- 'User-Agent': 'Mozilla/5.0 (compatible; ZhinBot/1.0)',
556
- 'Accept': 'text/html',
557
- 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
558
- },
559
- signal: AbortSignal.timeout(15000),
560
- });
561
- if (!res.ok) return `HTTP ${res.status}: ${res.statusText}`;
562
- const html = await res.text();
563
-
564
- // 从 DuckDuckGo HTML 页面提取搜索结果
565
- const results: { title: string; url: string; snippet: string }[] = [];
566
- const resultBlocks = html.split(/class="result\s/);
567
-
568
- for (let i = 1; i < resultBlocks.length && results.length < limit; i++) {
569
- const block = resultBlocks[i];
570
-
571
- // 提取标题和 URL
572
- const titleMatch = block.match(/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/);
573
- if (!titleMatch) continue;
574
-
575
- let href = titleMatch[1];
576
- // DuckDuckGo 会将 URL 编码到 uddg 参数中
577
- const uddgMatch = href.match(/[?&]uddg=([^&]+)/);
578
- if (uddgMatch) href = decodeURIComponent(uddgMatch[1]);
579
-
580
- const title = titleMatch[2].replace(/<[^>]+>/g, '').trim();
581
-
582
- // 提取摘要
583
- const snippetMatch = block.match(/<a[^>]*class="result__snippet"[^>]*>([\s\S]*?)<\/a>/);
584
- const snippet = snippetMatch
585
- ? snippetMatch[1].replace(/<[^>]+>/g, '').trim()
586
- : '';
587
-
588
- if (title && href) {
589
- results.push({ title, url: href, snippet });
590
- }
591
- }
592
-
593
- // 域名过滤
594
- let filtered = results;
595
- if (args.allowed_domains?.length) {
596
- const allowed = new Set((args.allowed_domains as string[]).map(d => d.toLowerCase()));
597
- filtered = filtered.filter(r => {
598
- try { return allowed.has(new URL(r.url).hostname.toLowerCase()); } catch { return false; }
599
- });
600
- }
601
- if (args.blocked_domains?.length) {
602
- const blocked = new Set((args.blocked_domains as string[]).map(d => d.toLowerCase()));
603
- filtered = filtered.filter(r => {
604
- try { return !blocked.has(new URL(r.url).hostname.toLowerCase()); } catch { return true; }
605
- });
606
- }
607
-
608
- if (filtered.length === 0) return 'No results found.';
609
- return `(${searchCount}/${MAX_SEARCH_COUNT} searches)\n` + filtered.map((r, i) =>
610
- `${i + 1}. ${r.title}\n URL: ${r.url}\n ${r.snippet}`,
611
- ).join('\n\n');
612
- } catch (e: unknown) {
613
- return `Error: ${errMsg(e)}`;
614
- }
615
- }),
616
- );
617
-
618
- // ── web_fetch(抓取 URL 并提取正文 + SSRF 防护 + 改进的内容提取) ──
619
- tools.push(
620
- new ZhinTool('web_fetch')
621
- .desc('抓取指定 URL 的网页内容并提取正文(去除广告、脚本等),返回可读文本。仅支持 http/https 协议。')
622
- .keyword('抓取网页', '打开链接', '获取网页', '读网页', 'fetch', 'url', '链接内容', '网页内容')
623
- .tag('web', 'fetch')
624
- .kind('web')
625
- .param('url', { type: 'string', description: '要抓取的完整 URL(需 http 或 https)' }, true)
626
- .param('max_length', { type: 'number', description: '最大返回字符数(默认 20480)' })
627
- .execute(async (args) => {
628
- try {
629
- // SSRF 防护:仅允许 http/https 协议
630
- let parsedUrl: URL;
631
- try {
632
- parsedUrl = new URL(args.url);
633
- } catch {
634
- return `Error: 无效的 URL 格式`;
635
- }
636
- if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
637
- return `Error: 仅支持 http/https 协议,拒绝 ${parsedUrl.protocol}`;
638
- }
639
- // 阻止内网地址(SSRF 关键防护)
640
- const hostname = parsedUrl.hostname.toLowerCase();
641
- if (
642
- hostname === 'localhost' ||
643
- hostname === '127.0.0.1' ||
644
- hostname === '::1' ||
645
- hostname === '0.0.0.0' ||
646
- hostname.endsWith('.local') ||
647
- hostname.startsWith('10.') ||
648
- hostname.startsWith('192.168.') ||
649
- /^172\.(1[6-9]|2\d|3[01])\./.test(hostname)
650
- ) {
651
- return `Error: 禁止访问内网地址 ${hostname}(SSRF 防护)`;
652
- }
653
-
654
- const response = await fetch(args.url, {
655
- headers: { 'User-Agent': 'Mozilla/5.0 (compatible; ZhinBot/1.0)' },
656
- signal: AbortSignal.timeout(15000),
657
- redirect: 'follow',
658
- });
659
- if (!response.ok) return `HTTP ${response.status}: ${response.statusText}`;
660
- const html = await response.text();
661
- // 改进的内容提取:去除脚本、样式、导航、页脚、表单等
662
- const text = html
663
- .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
664
- .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
665
- .replace(/<nav[^>]*>[\s\S]*?<\/nav>/gi, '')
666
- .replace(/<footer[^>]*>[\s\S]*?<\/footer>/gi, '')
667
- .replace(/<header[^>]*>[\s\S]*?<\/header>/gi, ' ')
668
- .replace(/<form[^>]*>[\s\S]*?<\/form>/gi, '')
669
- .replace(/<!--[\s\S]*?-->/g, '')
670
- .replace(/<[^>]+>/g, ' ')
671
- .replace(/&nbsp;/gi, ' ')
672
- .replace(/&amp;/g, '&')
673
- .replace(/&lt;/g, '<')
674
- .replace(/&gt;/g, '>')
675
- .replace(/&quot;/g, '"')
676
- .replace(/\s+/g, ' ')
677
- .trim();
678
- const maxLen = args.max_length ?? 20 * 1024;
679
- return text.length > maxLen ? text.slice(0, maxLen) + '\n...(truncated)' : text;
680
- } catch (e: unknown) {
681
- return `Error: ${errMsg(e)}`;
682
- }
683
- }),
684
- );
685
-
686
- // ── todo_read ──
687
- tools.push(
688
- new ZhinTool('todo_read')
689
- .desc('读取当前任务计划列表,用于查看进度和待办事项')
690
- .keyword('任务', '计划', '进度', 'todo', '待办')
691
- .tag('plan', 'todo')
692
- .kind('plan')
693
- .param('chat_id', { type: 'string', description: '聊天范围(传 "global" 表示全局,或传具体聊天 ID)' }, true)
694
- .execute(async (args) => {
695
- try {
696
- const dir = args.chat_id && args.chat_id !== 'global' ? path.join(DATA_DIR, 'groups', args.chat_id) : DATA_DIR;
697
- const todoPath = path.join(dir, 'TODO.json');
698
- if (!fs.existsSync(todoPath)) return 'No tasks found. Use todo_write to create a plan.';
699
- const data = JSON.parse(await fs.promises.readFile(todoPath, 'utf-8'));
700
- if (!data.items || data.items.length === 0) return 'Task list is empty.';
701
- const lines = data.items.map((item: any, i: number) => {
702
- const status = item.status === 'done' ? '✅' : item.status === 'in-progress' ? '🔄' : '⬜';
703
- return `${status} ${i + 1}. ${item.title}${item.detail ? ' — ' + item.detail : ''}`;
704
- });
705
- return `📋 Tasks (${data.items.filter((i: any) => i.status === 'done').length}/${data.items.length} done):\n${lines.join('\n')}`;
706
- } catch (e: unknown) {
707
- return `Error: ${errMsg(e)}`;
708
- }
709
- }),
710
- );
711
-
712
- // ── todo_write ──
713
- tools.push(
714
- new ZhinTool('todo_write')
715
- .desc('创建或更新任务计划,用于分解复杂任务并跟踪进度')
716
- .keyword('创建计划', '更新任务', '标记完成', 'todo')
717
- .tag('plan', 'todo')
718
- .kind('plan')
719
- .param('items', { type: 'array', description: '任务列表 [{title, detail?, status: pending|in-progress|done}]' } as PropertySchema<unknown[]>, true)
720
- .param('chat_id', { type: 'string', description: '聊天范围(可选)' })
721
- .execute(async (args) => {
722
- try {
723
- const dir = args.chat_id ? path.join(DATA_DIR, 'groups', args.chat_id) : DATA_DIR;
724
- const todoPath = path.join(dir, 'TODO.json');
725
- await fs.promises.mkdir(path.dirname(todoPath), { recursive: true });
726
- const data = { updated_at: new Date().toISOString(), items: args.items };
727
- await fs.promises.writeFile(todoPath, JSON.stringify(data, null, 2), 'utf-8');
728
- const done = args.items.filter((i: any) => i.status === 'done').length;
729
- return `✅ Tasks updated (${done}/${args.items.length} done)`;
730
- } catch (e: unknown) {
731
- return `Error: ${errMsg(e)}`;
732
- }
733
- }),
734
- );
735
-
736
- // ── read_memory ──
737
- tools.push(
738
- new ZhinTool('read_memory')
739
- .desc('读取持久化记忆(AGENTS.md)。记忆跨会话保持。scope: global(共享)或 chat(按聊天隔离)')
740
- .keyword('记忆', '记住', '回忆', '之前', '上次', 'memory')
741
- .tag('memory', 'agents')
742
- .kind('memory')
743
- .param('scope', { type: 'string', description: "'global' 或 'chat'(默认 chat)", enum: ['global', 'chat'] }, true)
744
- .param('chat_id', { type: 'string', description: '聊天 ID(chat scope 时使用)' })
745
- .execute(async (args) => {
746
- try {
747
- const memPath = args.scope === 'global'
748
- ? path.join(DATA_DIR, 'AGENTS.md')
749
- : path.join(DATA_DIR, 'groups', args.chat_id || 'default', 'AGENTS.md');
750
- if (!fs.existsSync(memPath)) return 'No memory stored yet.';
751
- return await fs.promises.readFile(memPath, 'utf-8');
752
- } catch (e: unknown) {
753
- return `Error: ${errMsg(e)}`;
754
- }
755
- }),
756
- );
757
-
758
- // ── write_memory ──
759
- tools.push(
760
- new ZhinTool('write_memory')
761
- .desc('写入持久化记忆。当用户说"记住…"、"记录…"时使用此工具')
762
- .keyword('记住', '保存', 'remember', '记录')
763
- .tag('memory', 'agents')
764
- .kind('memory')
765
- .param('content', { type: 'string', description: '要保存的记忆内容(Markdown)' }, true)
766
- .param('scope', { type: 'string', description: "'global' 或 'chat'(默认 chat)", enum: ['global', 'chat'] })
767
- .param('chat_id', { type: 'string', description: '聊天 ID' })
768
- .execute(async (args) => {
769
- try {
770
- const memPath = args.scope === 'global'
771
- ? path.join(DATA_DIR, 'AGENTS.md')
772
- : path.join(DATA_DIR, 'groups', args.chat_id || 'default', 'AGENTS.md');
773
- await fs.promises.mkdir(path.dirname(memPath), { recursive: true });
774
- await fs.promises.writeFile(memPath, args.content, 'utf-8');
775
- return `✅ Memory saved (${args.scope || 'chat'} scope)`;
776
- } catch (e: unknown) {
777
- return `Error: ${errMsg(e)}`;
778
- }
779
- }),
780
- );
781
-
782
- // ── activate_skill ──
783
- tools.push(
784
- new ZhinTool('activate_skill')
785
- .desc('按名称激活技能,加载其完整指令。当判断某个技能与用户请求相关时使用')
786
- .keyword('技能', '激活', '启用', '使用', 'skill', 'activate', 'use')
787
- .tag('skill', 'activate')
788
- .kind('skill')
789
- .param('name', { type: 'string', description: '技能名称' }, true)
790
- .execute(async (args) => {
791
- try {
792
- // 优先查找 SkillFeature 中已注册技能的 filePath
793
- const registeredPath = skillFileLookup?.(args.name);
794
- if (registeredPath && fs.existsSync(registeredPath)) {
795
- const fullContent = await fs.promises.readFile(registeredPath, 'utf-8');
796
- const depWarning = await checkSkillDeps(fullContent);
797
- const instructions = extractSkillInstructions(args.name, fullContent, skillMaxChars);
798
- return depWarning ? `${depWarning}\n\n${instructions}` : instructions;
799
- }
800
- for (const dir of skillDirList()) {
801
- const skillPath = path.join(dir, args.name, 'SKILL.md');
802
- if (fs.existsSync(skillPath)) {
803
- const fullContent = await fs.promises.readFile(skillPath, 'utf-8');
804
- const depWarning = await checkSkillDeps(fullContent);
805
- const instructions = extractSkillInstructions(args.name, fullContent, skillMaxChars);
806
- return depWarning ? `${depWarning}\n\n${instructions}` : instructions;
807
- }
808
- }
809
- return `Skill '${args.name}' not found. Check skills/ directory.`;
810
- } catch (e: unknown) {
811
- return `Error: ${errMsg(e)}`;
812
- }
813
- }),
814
- );
815
-
816
- // ── install_skill(从 URL 下载并安装技能) ──
817
- tools.push(
818
- new ZhinTool('install_skill')
819
- .desc('从 URL 下载 SKILL.md 并安装到本地 skills/ 目录。用户要求加入/安装/下载某个技能时使用')
820
- .keyword('安装技能', '下载技能', '加入', '添加技能', 'install', 'skill', 'join', '学会', '学习技能')
821
- .tag('skill', 'install')
822
- .kind('skill')
823
- .param('url', { type: 'string', description: 'SKILL.md 文件的完整 URL(如 https://example.com/skill.md)' }, true)
824
- .execute(async (args) => {
825
- try {
826
- const response = await fetch(args.url, {
827
- headers: { 'User-Agent': 'Mozilla/5.0 (compatible; ZhinBot/1.0)' },
828
- signal: AbortSignal.timeout(15000),
829
- });
830
- if (!response.ok) return `Error: HTTP ${response.status} ${response.statusText}`;
831
- const content = await response.text();
832
-
833
- const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---/);
834
- if (!fmMatch) return 'Error: 无效的 SKILL.md 文件(缺少 frontmatter)';
835
-
836
- let jsYaml: any;
837
- try {
838
- jsYaml = await import('js-yaml');
839
- if (jsYaml.default) jsYaml = jsYaml.default;
840
- } catch {
841
- return 'Error: 无法加载 yaml 解析器';
842
- }
843
-
844
- const metadata = jsYaml.load(fmMatch[1]);
845
- if (!metadata?.name) return 'Error: SKILL.md 缺少 name 字段';
846
-
847
- const skillName: string = metadata.name;
848
- const skillDir = path.join(process.cwd(), 'skills', skillName);
849
- await fs.promises.mkdir(skillDir, { recursive: true });
850
- const skillPath = path.join(skillDir, 'SKILL.md');
851
- await fs.promises.writeFile(skillPath, content, 'utf-8');
852
-
853
- logger.info(`技能已安装: ${skillName} → ${skillPath}`);
854
- return `✅ 技能「${skillName}」已安装到 ${skillPath}。现在可以用 activate_skill("${skillName}") 激活它。`;
855
- } catch (e: unknown) {
856
- return `Error: ${errMsg(e)}`;
857
- }
858
- }),
859
- );
860
-
861
- // ── ask_user(基于 Prompt 类的用户确认/提问工具) ──
862
- // 安全策略:在群聊中 ask_user 只向 owner 私聊确认,防止非 owner 用户操控安全敏感决策
863
- tools.push(
864
- new ZhinTool('ask_user')
865
- .desc('向 Bot Owner 发送问题并等待回复。用于需要确认、补充信息或做出选择时。在群聊中始终通过私聊向 Owner 确认,确保安全性。')
866
- .keyword('询问', '确认', '提问', '用户输入', 'ask', 'confirm', 'prompt', '选择', '请问')
867
- .tag('interaction', 'prompt')
868
- .kind('interaction')
869
- .param('question', { type: 'string', description: '要向 Owner 提出的问题文本' }, true)
870
- .param('type', { type: 'string', description: '问题类型: text(文本输入)、number(数字输入)、confirm(是/否确认)、pick(选项选择)。默认 text' })
871
- .param('options', { type: 'array', description: '选项列表(type=pick 时必填),每项为字符串,如 ["选项A","选项B","选项C"]' })
872
- .param('default_value', { type: 'string', description: 'Owner 超时未回复时使用的默认值' })
873
- .param('timeout', { type: 'number', description: '等待 Owner 回复的超时时间(秒),默认 120' })
874
- .execute(async (args, context) => {
875
- if (!context?.message) {
876
- return 'Error: 当前上下文没有消息来源,无法向 Owner 提问。请改为在回复中直接询问。';
877
- }
878
- if (!pluginRef) {
879
- return 'Error: 插件实例不可用,无法创建交互式提问。请改为在回复中直接询问。';
880
- }
881
-
882
- const timeoutMs = (args.timeout ?? 120) * 1000;
883
- const questionType = args.type || 'text';
884
-
885
- // 从 adapter 的 bot 配置中查找 owner
886
- const platform = context.platform!;
887
- const botId = context.botId!;
888
- const adapter = pluginRef.inject(platform) as Adapter | undefined;
889
- const bot = adapter?.bots?.get(botId);
890
- const botOwner: string | undefined = (bot?.$config as any)?.owner;
891
- const isPrivateOwner = context.scope === 'private'
892
- && botOwner != null && String(context.senderId) === String(botOwner);
893
-
894
- // ── 私聊 + 发送者是 Owner → 直接用 Prompt(原有行为) ──
895
- if (isPrivateOwner) {
896
- return askViaPrompt(pluginRef, context.message, args, questionType, timeoutMs);
897
- }
898
-
899
- // ── 非私聊 Owner → 必须通过私聊向 Owner 确认 ──
900
- if (!botOwner) {
901
- return 'Error: 当前 Bot 未配置 owner,无法进行安全确认。请在 bots 配置中设置 owner 字段。';
902
- }
903
-
904
- if (!adapter || typeof adapter.sendMessage !== 'function') {
905
- return `Error: 无法获取适配器 ${platform},无法向 Owner 发送私聊确认。`;
906
- }
907
-
908
- // 构建发送给 Owner 的问题文本(包含来源上下文)
909
- const sourceInfo = context.scope !== 'private'
910
- ? `来源: ${context.scope}(${context.sceneId}) 用户: ${context.senderId}`
911
- : `来源: 私聊 用户: ${context.senderId}`;
912
- let questionText = `🔐 AI 安全确认\n${sourceInfo}\n\n${args.question}`;
913
- if (questionType === 'confirm') {
914
- questionText += '\n输入"yes"以确认';
915
- } else if (questionType === 'pick' && args.options?.length) {
916
- questionText += '\n' + (args.options as string[]).map((o, i) => `${i + 1}.${o}`).join('\n');
917
- } else if (questionType === 'number') {
918
- questionText += '\n(请输入数字)';
919
- }
920
-
921
- try {
922
- await adapter.sendMessage({
923
- context: platform,
924
- bot: botId,
925
- id: botOwner,
926
- type: 'private',
927
- content: questionText,
928
- } satisfies SendOptions);
929
- } catch (e: unknown) {
930
- return `Error: 无法向 Owner 发送私聊消息: ${errMsg(e)}`;
931
- }
932
-
933
- // 注册一次性中间件等待 Owner 私聊回复
934
- return new Promise<string>((resolve) => {
935
- const middleware: MessageMiddleware = async (message, next) => {
936
- if (message.$channel?.type !== 'private') return next();
937
- if (String(message.$sender.id) !== String(botOwner)) return next();
938
- if (String(message.$bot) !== String(botId)) return next();
939
- dispose();
940
- clearTimeout(timer);
941
- const raw = message.$raw;
942
- resolve(formatOwnerResponse(raw, questionType, args));
943
- };
944
- const dispose = pluginRef!.addMiddleware(middleware);
945
- const timer = setTimeout(() => {
946
- dispose();
947
- if (args.default_value != null) {
948
- resolve(String(args.default_value));
949
- } else {
950
- resolve('Owner 未在规定时间内响应,操作已取消。');
951
- }
952
- }, timeoutMs);
953
- });
954
- }),
955
- );
956
-
957
- return tools;
958
- }