30f35a6562
- 重命名 grep_content.ts 为 grep.ts - 更新工具名称从 grep_content 改为 grep - 更新所有引用该工具的代码和测试文件 - 更新描述文件名称
@ai-assistant/core
Core engine package for AI Terminal Assistant - provides the AI agent, tools, and integrations.
📦 Installation
pnpm add @ai-assistant/core
🌟 Features
- AI Agent Engine - Streaming text generation with Claude API
- Tool System - Extensible tool registry with Zod validation
- Editor Modes - Multiple editing strategies (whole, diff, search-replace)
- Language Server Protocol - Code intelligence and analysis
- Checkpoint System - Shadow Git for safe experimentation
- Hook System - Pre/post execution customization
- Model Context Protocol - MCP client for external tools
- Repository Mapping - Tree-sitter based code analysis
🏗️ Architecture
src/
├── core/
│ ├── agent.ts # Main Agent class with streaming
│ ├── config.ts # Configuration management
│ └── types.ts # Core type definitions
├── tools/
│ ├── registry.ts # Tool registration system
│ ├── bash.ts # Bash command execution
│ ├── file.ts # File operations
│ ├── search.ts # Code search utilities
│ └── index.ts # Tool exports
├── editors/
│ ├── base.ts # Base editor interface
│ ├── whole.ts # Whole file replacement
│ ├── diff.ts # Diff-based editing
│ └── search-replace.ts # Search and replace
├── lsp/
│ ├── client.ts # LSP client implementation
│ └── server.ts # LSP server management
├── checkpoint/
│ ├── manager.ts # Checkpoint management
│ └── git.ts # Shadow Git operations
├── hooks/
│ ├── manager.ts # Hook execution system
│ └── types.ts # Hook type definitions
├── mcp/
│ ├── client.ts # MCP client implementation
│ └── protocol.ts # Protocol definitions
└── repomap/
├── generator.ts # Repository map generation
└── parser.ts # Tree-sitter parsing
🚀 Quick Start
Basic Usage
import { Agent, toolRegistry } from '@ai-assistant/core';
// Create an agent instance
const agent = new Agent({
apiKey: process.env.ANTHROPIC_API_KEY,
model: 'claude-sonnet-4-20250514',
maxTokens: 4096
});
// Chat with the agent
const response = await agent.chat('Help me write a TypeScript function', {
onChunk: (chunk) => console.log(chunk),
onComplete: (response) => console.log('Done:', response)
});
Tool Registration
import { toolRegistry } from '@ai-assistant/core/tools';
import { z } from 'zod';
// Register a custom tool
toolRegistry.register({
name: 'my_tool',
description: 'Does something useful',
parameters: z.object({
input: z.string().describe('Input parameter')
}),
execute: async (params) => {
// Tool implementation
return { success: true, result: params.input.toUpperCase() };
}
});
Editor Modes
import { createEditor } from '@ai-assistant/core/editors';
// Whole file replacement
const wholeEditor = createEditor('whole');
await wholeEditor.edit('file.ts', 'new content');
// Diff-based editing
const diffEditor = createEditor('diff');
await diffEditor.edit('file.ts', '--- old\n+++ new\n...');
// Search and replace
const searchEditor = createEditor('search-replace');
await searchEditor.edit('file.ts', {
search: 'oldFunction',
replace: 'newFunction'
});
Checkpoint System
import { CheckpointManager } from '@ai-assistant/core/checkpoint';
const manager = new CheckpointManager('/project/path');
// Create a checkpoint
await manager.create('before-refactoring');
// Make changes...
// Restore if needed
await manager.restore('before-refactoring');
// List checkpoints
const checkpoints = await manager.list();
Language Server Protocol
import { LSPClient } from '@ai-assistant/core/lsp';
const lsp = new LSPClient({
serverCommand: 'typescript-language-server',
serverArgs: ['--stdio']
});
await lsp.initialize('/project/path');
// Get diagnostics
const diagnostics = await lsp.getDiagnostics('file.ts');
// Get completions
const completions = await lsp.getCompletions('file.ts', { line: 10, character: 5 });
// Go to definition
const definition = await lsp.getDefinition('file.ts', { line: 10, character: 5 });
🔧 Configuration
interface AgentConfig {
apiKey: string; // Anthropic API key
model?: string; // Model name (default: claude-sonnet-4-20250514)
maxTokens?: number; // Max response tokens (default: 4096)
temperature?: number; // Sampling temperature (default: 0.7)
systemPrompt?: string; // System prompt
tools?: Tool[]; // Available tools
hooks?: HookConfig; // Hook configuration
checkpointDir?: string; // Checkpoint directory
}
📚 API Reference
Agent
class Agent {
constructor(config: AgentConfig);
chat(message: string, options?: ChatOptions): Promise<Response>;
streamChat(message: string, options?: StreamOptions): AsyncIterator<Chunk>;
reset(): void;
getHistory(): Message[];
}
Tool Registry
class ToolRegistry {
register(tool: ToolDefinition): void;
unregister(name: string): void;
get(name: string): Tool | undefined;
list(): Tool[];
execute(name: string, params: any): Promise<ToolResult>;
}
Editor Interface
interface Editor {
edit(path: string, content: string | EditParams): Promise<void>;
validate(content: string): boolean;
preview(path: string, content: string): string;
}
🧪 Testing
# Run tests
pnpm test
# Run with coverage
pnpm test:coverage
# Watch mode
pnpm test:watch
🤝 Contributing
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
📄 License
MIT License - see LICENSE for details.