bc1ece3dad
- 新增 ToolRegistry 工具注册表,支持核心工具和延迟加载工具分离 - 新增 tool_search 元工具,支持关键词搜索发现可用工具 - 新增基于关键词的搜索算法,按相关度评分排序 - 为所有工具添加 metadata(分类、关键词、延迟加载标识) - 修改 Agent 支持动态工具注入,tool_search 结果自动添加到可用工具 - 核心工具(tool_search, bash)始终加载,其他工具按需发现
100 lines
2.9 KiB
TypeScript
100 lines
2.9 KiB
TypeScript
import * as fs from 'fs/promises';
|
||
import * as path from 'path';
|
||
import type { ToolResult } from '../../types/index.js';
|
||
import type { ToolWithMetadata } from '../types.js';
|
||
import { loadDescription } from '../load_description.js';
|
||
import { getPermissionManager } from '../../permission/index.js';
|
||
|
||
export const deleteFileTool: ToolWithMetadata = {
|
||
name: 'delete_file',
|
||
description: loadDescription('delete_file'),
|
||
metadata: {
|
||
name: 'delete_file',
|
||
category: 'filesystem',
|
||
description: '删除文件或目录',
|
||
keywords: ['delete', 'remove', 'file', 'rm', '删除', '移除', '文件'],
|
||
deferLoading: true,
|
||
},
|
||
parameters: {
|
||
path: {
|
||
type: 'string',
|
||
description: '要删除的文件或目录的路径',
|
||
required: true,
|
||
},
|
||
recursive: {
|
||
type: 'boolean',
|
||
description: '是否递归删除目录(默认 false)',
|
||
required: false,
|
||
},
|
||
},
|
||
execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
|
||
const filePath = params.path as string;
|
||
const recursive = (params.recursive as boolean) || false;
|
||
const cwd = process.cwd();
|
||
|
||
const absolutePath = path.isAbsolute(filePath)
|
||
? filePath
|
||
: path.join(cwd, filePath);
|
||
|
||
// 权限检查
|
||
const permissionManager = getPermissionManager();
|
||
const permResult = await permissionManager.checkFilePermission({
|
||
operation: 'delete',
|
||
path: absolutePath,
|
||
workdir: cwd,
|
||
});
|
||
|
||
if (!permResult.allowed) {
|
||
if (permResult.needsConfirmation) {
|
||
return {
|
||
success: false,
|
||
output: '',
|
||
error: `需要用户确认: 删除 ${absolutePath}\n原因: ${permResult.reason || '需要权限确认'}`,
|
||
};
|
||
}
|
||
return {
|
||
success: false,
|
||
output: '',
|
||
error: `权限被拒绝: ${permResult.reason || '不允许删除此文件'}`,
|
||
};
|
||
}
|
||
|
||
try {
|
||
const stats = await fs.stat(absolutePath);
|
||
|
||
if (stats.isDirectory()) {
|
||
if (!recursive) {
|
||
// 检查目录是否为空
|
||
const entries = await fs.readdir(absolutePath);
|
||
if (entries.length > 0) {
|
||
return {
|
||
success: false,
|
||
output: '',
|
||
error: `目录不为空。如需删除非空目录,请设置 recursive: true`,
|
||
};
|
||
}
|
||
await fs.rmdir(absolutePath);
|
||
} else {
|
||
await fs.rm(absolutePath, { recursive: true });
|
||
}
|
||
return {
|
||
success: true,
|
||
output: `已删除目录: ${absolutePath}`,
|
||
};
|
||
} else {
|
||
await fs.unlink(absolutePath);
|
||
return {
|
||
success: true,
|
||
output: `已删除文件: ${absolutePath}`,
|
||
};
|
||
}
|
||
} catch (error) {
|
||
return {
|
||
success: false,
|
||
output: '',
|
||
error: error instanceof Error ? error.message : String(error),
|
||
};
|
||
}
|
||
},
|
||
};
|