跳转到主要内容
AG-Kit 的文件系统工具为您的 Agent 提供了与文件交互的全面可靠方案。通过支持事务处理、多种后端和统一工具包,它专为构建执行基于文件任务的稳健 Agent 而设计。

功能概览

使用此工具包可让您的 Agent 具备以下能力:
  • 原子操作:安全地同时修改多个文件,失败时自动回滚。
  • 管理文件与目录:创建、读取、更新、删除及列出文件和目录。
  • 文件系统搜索:通过名称(glob)或内容(grep)查找文件。
  • 安全环境运行:根据安全需求选择本地、内存或沙盒后端。

核心概念

  1. FilesystemToolkit:主要入口点,集成了可供 Agent 直接使用的文件相关工具集(read_filewrite_file 等)。
  2. FileOperator(后端):执行实际文件操作的引擎,提供三种后端选择:
    • LocalFileOperator:高性能访问本地文件系统。
    • InMemoryFileOperator:在虚拟文件系统中进行快速隔离测试。
    • SandboxFileOperator:在隔离容器中安全执行,适合处理不可信代码。

快速入门

import { FilesystemToolkit, LocalFileOperator } from '@ag-kit/tools';

// 1. 选择后端并创建工具包
const operator = new LocalFileOperator();
const fsToolkit = new FilesystemToolkit({
  name: 'fs',
  context: { workingDirectory: process.cwd(), fsOperator: operator },
});

// 2. 获取工具并使用
const writeTool = fsToolkit.getTool('write_file');
await writeTool.invoke({ 
  file_path: 'greeting.txt', 
  content: 'Hello 
});

关键特性:原子事务

对于代码生成等复杂任务,常需修改多个文件。若某步失败,可能导致项目处于损坏状态。事务机制通过”全成功或全回滚”确保数据一致性。 withTransaction 内任何操作失败,所有变更将自动回滚。
import { withTransaction } from '@ag-kit/tools/fs/operator/transaction';
import { LocalFileOperator } from '@ag-kit/tools';

const operator = new LocalFileOperator();

try {
  await withTransaction(operator, async (tx) => {
    // 以下操作具有原子性
    await tx.writeFile('src/component.js', '// New component code');
    await tx.writeFile('src/index.js', 'import "./component.js";');
    // 若此处失败,前述两个文件将被还原
    await tx.writeFile('package.json', 'invalid json'); 
  });
} catch (error) {
  console.log('事务失败已回滚:', error.message);
}
高级事务控制详见应用程序接口参考

核心操作

以下是工具包支持的主要操作。

写入与创建文件

write_file 工具可创建新文件或覆盖现有文件,若父目录不存在会自动创建。
const result = await fsToolkit.getTool('write_file').invoke({
  file_path: 'src/utils/helpers.ts',
  content: 'export const newUtil = () => {};'
});
// result.data: { file_path: 'src/utils/helpers.ts', bytes_written: 35 }

读取文件

read_file 工具可读取指定文件的全部内容。
const result = await fsToolkit.getTool('read_file').invoke({
  file_path: 'package.json'
});
// result.data: '{\n  "name": "my-app",\n  ...'
console.log(result.data.content);

编辑文件

edit_file 工具对文件内容执行查找替换,适合进行针对性修改。
const result = await fsToolkit.getTool('edit_file').invoke({
  file_path: 'src/config.js',
  old_str: 'API_ENDPOINT = "http://dev.example.com"',
  new_str: 'API_ENDPOINT = "http://prod.example.com"'
});
// result.data: { file_path: 'src/config.js', replacements_made: 1 }

列出目录内容

ls 工具可列出指定路径下的文件和子目录。
const result = await fsToolkit.getTool('ls').invoke({ path: 'src' });
// result.data: { 
//   entries: [
//     { name: 'components', type: 'directory', size: 0 },
//     { name: 'utils', type: 'directory', size: 0 },
//     { name: 'index.ts', type: 'file', size: 1024 }
//   ]
// }
console.log(result.data.entries.map(e => e.name));

模式匹配查找(Glob)

glob 工具可查找匹配特定模式的所有文件和目录,便于预处理文件发现。
const result = await fsToolkit.getTool('glob').invoke({
  pattern: '**/*.test.ts'
});
// result.data: { 
//   matches: [
//     'src/utils/helpers.test.ts',
//     'src/components/Button.test.ts',
//     'tests/integration.test.ts'
//   ]
// }
console.log('发现测试文件:', result.data.matches);

文件内容搜索(Grep)

grep 工具可在指定目录文件中搜索文本模式(支持正则表达式),适用于定位函数调用或特定注释。
const result = await fsToolkit.getTool('grep').invoke({
  pattern: 'TODO|FIXME',
  path: 'src'
});
// result.data: {
//   matches: [
//     { file: 'src/utils/helpers.ts', line_number: 42, line_content: '  // TODO: Optimize this function' },
//     { file: 'src/components/Button.tsx', line_number: 15, line_content: '  // FIXME: Handle edge case' }
//   ]
// }

if (result.data.matches.length > 0) {
  console.log('Matches found:');
  result.data.matches.forEach(match => {
    console.log(`- ${match.file}:${match.line_number}: ${match.line_content.trim()}`);
  });
}
所有工具的详细输入输出模式,请参阅API参考

工作流示例:Agent集成

FilesystemToolkit直接集成到您的Agent中,为其提供强大的文件操作能力。
import { FilesystemToolkit, LocalFileOperator } from '@ag-kit/tools';

const fsToolkit = new FilesystemToolkit({
  name: 'fs',
  context: { workingDirectory: process.cwd(), fsOperator: new LocalFileOperator() },
});

const tools = fsToolkit.getTools();

后续步骤