Files
ai-terminal-assistant/packages/core
kurihada cb554c65b4 feat(checkpoint): 添加 Checkpoint 可视化管理功能
Core 层增强:
- 添加 safety.ts: 7点安全检查机制
- 添加 session-tracker.ts: 会话级检查点跟踪
- 添加 lock.ts: 并发控制文件锁
- 添加 lfs.ts: Git LFS 大文件支持
- 添加 path-validator.ts: 路径验证
- 添加 commit-message.ts: 智能提交消息生成
- 增强 manager.ts: 支持三种恢复模式、unrevert 撤销回滚

Server 层:
- 添加 checkpoints.ts: 16个 REST API 端点
  - GET/POST /checkpoints: 列表/创建检查点
  - GET/DELETE /checkpoints/🆔 获取/删除检查点
  - GET /checkpoints/:id/diff: 获取差异
  - POST /checkpoints/:id/restore: 恢复到检查点
  - POST /checkpoints/unrevert: 撤销回滚
  - GET /checkpoints/:id/safety-check: 安全检查

UI 层:
- 添加 CheckpointPanel.tsx: 检查点列表面板
- 添加 CheckpointDiffViewer.tsx: 差异查看器
- 添加 RestoreDialog.tsx: 恢复确认对话框
- 添加 16 个 API 客户端函数
- 添加完整的 TypeScript 类型定义

Web/Desktop 集成:
- 添加 History 按钮到工具栏
- 集成 CheckpointPanel 组件
2025-12-12 22:52:27 +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.