Skip to content

6. 文件系统与 Shell 工具

6.1 文件系统工具

typescript
const fileSystemTools = [
  {
    name: "file_read",
    description: `Read the contents of a file.

Supported formats:
- Text: .txt, .md, .json, .yaml, .xml, .csv
- Code: .py, .js, .ts, .java, .go, .rs, etc.
- Data: .pdf (text extraction), .xlsx (as JSON)

Returns file content as string or structured data.`,
    
    parameters: {
      type: "object",
      properties: {
        path: { type: "string", description: "File path to read" },
        encoding: { type: "string", default: "utf-8" }
      },
      required: ["path"]
    }
  },
  
  {
    name: "file_write",
    description: `Write content to a file. Creates directories if needed.

Best practices:
- Always save important results to files
- Use appropriate file extensions
- Prefer structured formats (JSON, CSV) for data`,
    
    parameters: {
      type: "object",
      properties: {
        path: { type: "string" },
        content: { type: "string" },
        mode: { 
          type: "string", 
          enum: ["write", "append"],
          default: "write"
        }
      },
      required: ["path", "content"]
    }
  },
  
  {
    name: "file_search",
    description: "Search for files by name pattern or content",
    parameters: {
      type: "object",
      properties: {
        directory: { type: "string", default: "." },
        pattern: { type: "string", description: "Glob pattern or regex" },
        contentMatch: { type: "string", description: "Search within file contents" }
      },
      required: ["pattern"]
    }
  },
  
  {
    name: "file_list",
    description: "List files and directories",
    parameters: {
      type: "object",
      properties: {
        path: { type: "string", default: "." },
        recursive: { type: "boolean", default: false }
      }
    }
  }
];

6.2 Shell 命令工具

typescript
const shellTools = [
  {
    name: "shell_exec",
    description: `Execute a shell command in the sandbox Linux environment.

Available tools:
- Python 3.x with common packages
- Node.js and npm
- Git, curl, wget
- Standard Linux utilities

Safety:
- Commands run in isolated sandbox
- Network access is available
- File changes persist within the sandbox session

Tips:
- Use && to chain commands
- Redirect output to files for large results
- Check exit codes for success/failure`,
    
    parameters: {
      type: "object",
      properties: {
        command: { type: "string" },
        workdir: { type: "string", description: "Working directory" },
        timeout: { type: "number", default: 300 }
      },
      required: ["command"]
    }
  },
  
  {
    name: "shell_python",
    description: `Execute Python code directly.

Pre-installed packages:
- Data: pandas, numpy, scipy
- Web: requests, beautifulsoup4, aiohttp  
- Utils: json, csv, datetime, re

For complex scripts, prefer writing to .py file first.`,
    
    parameters: {
      type: "object",
      properties: {
        code: { type: "string" },
        saveAs: { type: "string", description: "Optionally save script to file" }
      },
      required: ["code"]
    }
  }
];

6.3 文件操作实现

typescript
class FileSystemController {
  private basePath: string;
  
  constructor(sandboxPath: string) {
    this.basePath = sandboxPath;
  }
  
  async read(path: string): Promise<FileContent> {
    const fullPath = this.resolvePath(path);
    const ext = path.split('.').pop()?.toLowerCase();
    
    // 根据文件类型处理
    switch (ext) {
      case 'json':
        const json = await fs.readFile(fullPath, 'utf-8');
        return { type: 'json', data: JSON.parse(json) };
        
      case 'csv':
        const csv = await fs.readFile(fullPath, 'utf-8');
        return { type: 'csv', data: this.parseCSV(csv) };
        
      case 'pdf':
        const pdfText = await this.extractPdfText(fullPath);
        return { type: 'text', data: pdfText };
        
      default:
        const text = await fs.readFile(fullPath, 'utf-8');
        return { type: 'text', data: text };
    }
  }
  
  async write(path: string, content: string): Promise<void> {
    const fullPath = this.resolvePath(path);
    
    // 确保目录存在
    await fs.mkdir(dirname(fullPath), { recursive: true });
    
    await fs.writeFile(fullPath, content, 'utf-8');
  }
  
  async search(pattern: string, options: SearchOptions = {}): Promise<string[]> {
    const glob = require('fast-glob');
    const files = await glob(pattern, {
      cwd: this.basePath,
      ignore: ['node_modules/**', '.git/**']
    });
    
    if (options.contentMatch) {
      // 过滤包含指定内容的文件
      const matches = [];
      for (const file of files) {
        const content = await this.read(file);
        if (content.data.includes(options.contentMatch)) {
          matches.push(file);
        }
      }
      return matches;
    }
    
    return files;
  }
  
  private resolvePath(path: string): string {
    // 安全检查:防止路径遍历
    const resolved = resolve(this.basePath, path);
    if (!resolved.startsWith(this.basePath)) {
      throw new Error('Path traversal detected');
    }
    return resolved;
  }
}

前端面试知识库