Files
ai-terminal-assistant/packages/core
kurihada 48b458bb9a feat(core): 使用模板系统重构 plan 工具并完善 build agent 配置
- enter_plan_mode/exit_plan_mode 改用 loadDescription 加载描述
- 新增 plan 工具描述文件支持模板变量
- build agent 添加完整的工具启用列表和权限配置
- build agent 启用 promptTemplate 动态模板渲染
2025-12-17 11:52:52 +08:00
..
2025-12-12 14:28:34 +08:00
2025-12-12 15:31:38 +08:00

@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:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

📄 License

MIT License - see LICENSE for details.