JSPM

@kepoai/ai-file-tools

1.2.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 3
  • Score
    100M100P100Q60539F
  • License Apache-2.0

File operation tools for AI agents, extracted from Gemini CLI

Package Exports

  • @kepoai/ai-file-tools

Readme

@kepoai/ai-file-tools

npm version License: Apache-2.0 TypeScript Node.js

Professional file operation tools for AI agents - Extracted from Gemini CLI and enhanced with AI-powered features.

Empower your AI agents with a complete toolkit for exploring, analyzing, and modifying codebases. Built for production use with AI SDK v5.

English | 简体中文

📖 Documentation

Features

  • 🗂️ File Operations: Read, write, and edit files with AI assistance
  • 🔍 Search & Discovery: List directories, find files, search content
  • 🤖 AI-Powered: Built-in AI correction for edit operations
  • 🔒 Safe: Workspace-based path validation with .gitignore and .geminiignore support
  • Fast: LRU caching for AI corrections
  • 📦 Minimal: Few dependencies, clean API
  • 🔌 Flexible: Works with AI SDK v5 and OpenRouter

Installation

# Using pnpm (recommended)
pnpm add @kepoai/ai-file-tools

# Using npm
npm install @kepoai/ai-file-tools

# Using yarn
yarn add @kepoai/ai-file-tools

Quick Start

import { createOpenRouter } from '@openrouter/ai-sdk-provider';
import {
  createFileTools,
  createToolSchemas,
} from '@kepoai/ai-file-tools';
import { generateText } from 'ai';

// 1. Initialize AI client
const openrouter = createOpenRouter({
  apiKey: process.env.OPENROUTER_API_KEY,
});
const model = openrouter('anthropic/claude-3.5-sonnet');

// 2. Create file tools
const fileTools = createFileTools({
  workspaceDirs: ['/path/to/project'],
  aiClient: model,
  enableAiCorrection: true,
});

// 3. Create tool schemas (or use the helper function)

const toolSchemas = createToolSchemas(fileTools);

const result = await generateText({
  model,
  tools: toolSchemas,
  prompt: 'Find all TypeScript files in src/ that contain TODO comments',
});

console.log(result.text);

Available Tools

File Operations (5 tools)

📄 read_file

Read file contents with support for multiple formats:

  • Text files: JavaScript, TypeScript, Python, JSON, YAML, etc.
  • Images: PNG, JPG, GIF, WEBP, SVG, BMP (embedded as inline data)
  • PDFs: Extracts text content automatically
  • Large files: Pagination support with offset/limit

✏️ write_file

Write or overwrite entire file contents:

  • Displays diff preview before applying changes
  • Creates parent directories automatically
  • Returns statistics (lines added/removed)
  • Supports all text encodings

🔄 replace (EditTool)

Precise text replacement with AI-powered error correction:

  • Exact string matching with context
  • AI auto-correction for formatting issues (whitespace, indentation)
  • LRU cache for performance
  • Supports multiple replacements in one file

🎯 smart_edit (SmartEditTool)

Semantic code editing with natural language instructions:

  • Uses AI to understand edit intent
  • Generates precise old_string/new_string automatically
  • Ideal for complex refactoring
  • Combines AI reasoning with reliable text replacement

📚 read_many_files

Batch read multiple files efficiently:

  • Glob pattern matching (**/*.ts, src/**/*.{js,jsx})
  • Recursive directory traversal
  • File filtering (respects .gitignore/.geminiignore)
  • Returns all file contents in one call

Search & Discovery (3 tools)

📁 list_directory

List directory contents with intelligent filtering:

  • File and directory information (size, type, modified time)
  • Respects .gitignore and .geminiignore
  • Custom ignore patterns
  • Sorted output (directories first, then alphabetically)

🔍 glob

Find files by name patterns:

  • Full glob syntax support (**/*, *.{ts,tsx}, src/**/test_*.py)
  • Cross-workspace search
  • File filtering (excludes node_modules, .git, etc.)
  • Results sorted by modification time

🔎 search_file_content

Search file contents with regex:

  • Case-insensitive pattern matching
  • File type filtering (*.ts, *.py)
  • Line number and context
  • Performance limits (prevents searching large binary files)

Configuration

interface ToolConfig {
  workspaceDirs: string[];           // Required: workspace directories
  aiClient?: LanguageModelV1;        // Optional: AI SDK v5 client (required for AI correction)
  enableAiCorrection?: boolean;      // Optional: enable AI correction (default: true if aiClient provided)
  maxCacheSize?: number;             // Optional: cache size (default: 50)
  fileFiltering?: {
    respectGitIgnore?: boolean;      // Default: true - respects .gitignore patterns
    respectGeminiIgnore?: boolean;   // Default: true - respects .geminiignore patterns
  };
}

AI-Assisted Edit Correction

When edit operations fail to match exact text, the built-in AI corrector automatically:

  1. Detects common issues (whitespace, escaping, indentation)
  2. Calls a lightweight LLM to suggest corrections
  3. Caches results for performance
  4. Retries with corrected parameters

This dramatically improves the success rate of AI-generated edits.

📖 Read the full AI Correction documentation

License

Apache 2.0 - Extracted from Gemini CLI

Electron Integration Example

// main.ts (Electron Main Process)
import { ipcMain } from 'electron';
import { createOpenRouter } from '@openrouter/ai-sdk-provider';
import { createFileTools } from '@kepoai/ai-file-tools';
import { generateText } from 'ai';
import * as path from 'path';

// Initialize tools once
const openrouter = createOpenRouter({
  apiKey: process.env.OPENROUTER_API_KEY,
});
const model = openrouter('anthropic/claude-3.5-sonnet');

const fileTools = createFileTools({
  workspaceDirs: [path.join(app.getPath('documents'), 'MyProject')],
  aiClient: model,
  enableAiCorrection: true,
});

// Handle IPC requests from renderer
ipcMain.handle('ai-edit-file', async (event, prompt: string) => {
  const result = await generateText({
    model,
    tools: {
      read_file: readFileSchema(fileTools.readFile),
      replace: editSchema(fileTools.edit),
    },
    prompt,
  });
  
  return result;
});

Advanced Usage

Custom Tool Configuration

const fileTools = createFileTools({
  workspaceDirs: [
    '/path/to/project',
    '/path/to/another/workspace',
  ],
  aiClient: model,
  
  // Disable AI correction for faster execution
  enableAiCorrection: false,
  
  // Increase cache size for better performance
  maxCacheSize: 100,
  
  // Custom file filtering
  fileFiltering: {
    respectGitIgnore: true,
    respectGeminiIgnore: false,
  },
});

Using Individual Tools

import { ReadFileTool, EditTool, ToolsConfig } from '@kepoai/ai-file-tools';

const config = new ToolsConfig({
  workspaceDirs: ['/path/to/project'],
  aiClient: model,
});

const readTool = new ReadFileTool(config);
const editTool = new EditTool(config);

// Use tools directly
const fileContent = await readTool.execute({
  absolute_path: '/path/to/project/config.ts',
});

const editResult = await editTool.execute({
  file_path: '/path/to/project/config.ts',
  old_string: 'port: 3000',
  new_string: 'port: 8080',
});

Real-World Usage Examples

Example 1: Automated Code Refactoring

import { createFileTools, createToolSchemas } from '@kepoai/ai-file-tools';
import { generateText } from 'ai';

const tools = createFileTools({ workspaceDirs: ['/my-project'] });
const schemas = createToolSchemas(tools);

const result = await generateText({
  model,
  tools: schemas,
  prompt: `
    Find all functions in src/ that use the old 'getUserData' API 
    and refactor them to use the new 'fetchUserProfile' API instead.
  `,
});

Example 2: Fix Multiple Files

const result = await generateText({
  model,
  tools: schemas,
  prompt: `
    Search for all files containing 'console.log' in src/ 
    and replace them with proper logger.debug() calls.
  `,
});

Example 3: Generate New Feature

const result = await generateText({
  model,
  tools: schemas,
  prompt: `
    Analyze the project structure in src/features/
    and create a new feature module called 'notifications'
    following the same pattern as existing features.
  `,
});

FAQ

Q: Do I need to provide an AI client?

A: The aiClient is optional. It's only required if you want to enable AI-assisted edit correction. Without it, all tools work normally but won't auto-fix formatting issues in replace and smart_edit operations.

Q: What AI models are supported?

A: Any model compatible with AI SDK v5. Tested with:

  • Anthropic Claude (3.5 Sonnet, 3 Opus)
  • OpenAI GPT-4
  • Google Gemini (via OpenRouter)
  • Any OpenRouter-supported model

Q: How does file filtering work?

A: By default, the tools respect .gitignore and .geminiignore rules. This means:

  • node_modules/, .git/, dist/ are automatically excluded
  • You can add custom patterns in .geminiignore
  • You can disable filtering per-tool or globally in config

Q: Can I use this without AI SDK?

A: Yes! You can use the tools directly:

import { ReadFileTool, EditTool, ToolsConfig } from '@kepoai/ai-file-tools';

const config = new ToolsConfig({ workspaceDirs: ['/project'] });
const readTool = new ReadFileTool(config);

const result = await readTool.execute({ 
  absolute_path: '/project/src/index.ts' 
});
console.log(result.llmContent);

Q: Is this safe to use in production?

A: Yes. The package includes:

  • ✅ Workspace path validation (prevents access outside designated directories)
  • ✅ File filtering (respects .gitignore/.geminiignore)
  • ✅ No file deletion capabilities
  • ✅ Diff preview for write operations
  • ✅ TypeScript type safety

Q: What's the difference between replace and smart_edit?

A:

  • replace: You provide exact old_string and new_string. AI correction helps if the exact match fails (e.g., formatting issues).
  • smart_edit: You provide a natural language instruction. The AI figures out what to replace and generates both strings.

Use replace for precise, predictable edits. Use smart_edit for complex refactoring where you want the AI to reason about the change.


Contributing

We welcome contributions! Please see the Gemini CLI contributing guide.

Development

# Clone the repo
git clone https://github.com/google-gemini/gemini-cli.git
cd gemini-cli/ai-file-tools

# Install dependencies
pnpm install

# Build
pnpm run build

# Run tests
pnpm test

# Type check
pnpm run typecheck

Support & Issues


Status

✅ Production Ready (v1.0.0)

Feature Status
File Operations ✅ Complete
Search & Discovery ✅ Complete
AI Correction ✅ Complete
File Filtering (.gitignore/.geminiignore) ✅ Complete
AI SDK v5 Integration ✅ Complete
TypeScript Support ✅ Complete
Documentation ✅ Complete

Roadmap

Completed ✅

  • Core file operations (8 tools)
  • AI SDK v5 integration
  • OpenRouter support
  • AI-powered edit correction
  • File filtering (.gitignore/.geminiignore)
  • Search and discovery tools
  • Integration test suite (ai-correction, real-ai, e2e, proof tests)

In Progress 🚧

  • Unit test coverage (partially complete)

Future Enhancements 🔮

  • Performance benchmarks
  • File deletion/rename tools
  • Direct RipGrep integration (optional)
  • Streaming support for large files

License

Apache 2.0 - Extracted and enhanced from Gemini CLI

Copyright 2025 Google LLC (original Gemini CLI code)
Copyright 2025 Kepo AI (enhancements and packaging)


Acknowledgments

This package is built upon the excellent work of the Gemini CLI team at Google. We've extracted and enhanced the core file operation tools to make them available as a standalone package for the AI agent development community.


Made with ❤️ by Kepo AI