docs: 更新项目文档

This commit is contained in:
2025-12-12 14:28:34 +08:00
parent 2fe1c55997
commit b17649930b
6 changed files with 1894 additions and 128 deletions
+172 -128
View File
@@ -1,180 +1,224 @@
# AI Terminal Assistant # AI Terminal Assistant
**由 kurihada 开发** <div align="center">
<h3>🤖 A powerful terminal-based AI coding assistant powered by Claude API</h3>
<p>
<a href="#features">Features</a> •
<a href="#quick-start">Quick Start</a> •
<a href="#documentation">Documentation</a> •
<a href="#packages">Packages</a>
</p>
<p>
<img alt="License" src="https://img.shields.io/badge/license-MIT-blue.svg">
<img alt="Node" src="https://img.shields.io/badge/node-%3E%3D18.0.0-green">
<img alt="pnpm" src="https://img.shields.io/badge/pnpm-%3E%3D8.0.0-orange">
</p>
</div>
一个运行在终端中的 AI 编程助手,基于 Claude API 构建。可以帮助您读取和写入文件、执行 bash 命令、搜索代码和文件、回答编程问题等。 ## 🌟 Overview
## ✨ 特性 AI Terminal Assistant is a comprehensive AI-powered development toolkit that helps developers write code, debug issues, and manage projects more efficiently. Built as a modular monorepo, it provides multiple interfaces (CLI, Web, Desktop) to interact with Claude AI for various programming tasks.
- 🚀 **终端原生体验**:直接在终端中与 AI 交互 ## ✨ Features
- 🔧 **强大的工具集**
- 文件读写操作
- Bash 命令执行
- 目录列表和文件搜索
- 代码分析和建议
- 🛡️ **安全第一**:在执行可能有风险的命令前会请求确认
- 💬 **两种模式**
- 交互模式:持续对话
- 单次提问模式:快速获取答案
- ⚙️ **可配置**:支持多种 AI 模型和参数配置
## 📦 安装 ### Core Capabilities
- 🧠 **Advanced AI Agent** - Powered by Claude API with streaming responses
- 🔧 **Rich Tool System** - File operations, bash commands, code search, and more
- 📝 **Smart Code Editing** - Multiple edit modes (whole, diff, search-replace)
- 🔍 **Language Server Protocol** - IDE-like code intelligence
- 💾 **Checkpoint System** - Shadow Git for safe experimentation
- 🔌 **Model Context Protocol** - Extensible tool integration
- 🎣 **Hook System** - Pre/post execution customization
### 前提条件 ### User Interfaces
- Node.js 18+ - 🖥️ **CLI** - Terminal-native experience with serve/attach modes
- 🌐 **Web UI** - Modern React interface with real-time updates
- 🖱️ **Desktop App** - Tauri-based native application (Coming soon)
### Developer Experience
- 📦 **Monorepo Architecture** - Clean separation of concerns
- 🚀 **Built with Bun** - Fast runtime and bundling
- 🔥 **Hot Reload** - Development with instant feedback
- 🧪 **Comprehensive Testing** - Unit and integration tests
- 📊 **Type Safety** - Full TypeScript support
## 🚀 Quick Start
### Prerequisites
- Node.js 18+ or Bun 1.0+
- pnpm 8.0+
- Anthropic API Key - Anthropic API Key
### 全局安装 ### Installation
```bash
npm install -g .
```
### 本地开发
```bash ```bash
# 克隆项目 # Clone the repository
git clone <your-repo-url> git clone <repository-url>
cd ai-terminal-assistant cd ai-terminal-assistant
# 安装依赖 # Install dependencies
npm install pnpm install
# 构建项目 # Set up environment variables
npm run build cp .env.example .env
# Edit .env and add your ANTHROPIC_API_KEY
# 链接到全局 # Build all packages
npm link pnpm build
``` ```
## 🚀 快速开始 ### Running the Application
### 1. 初始化配置 #### Option 1: Web Interface
```bash ```bash
ai-assist init # Start the server
``` pnpm server:dev
按照提示设置您的 Anthropic API Key。
### 2. 启动交互模式 # In another terminal, start the web UI
pnpm web:dev
# Open http://localhost:5173 in your browser
```
#### Option 2: CLI Mode
```bash ```bash
ai-assist # Start the server
cd packages/cli && bun run src/index.ts serve --port 3000
# In another terminal, attach to the server
cd packages/cli && bun run src/index.ts attach http://localhost:3000
``` ```
### 3. 单次提问模式 ## 📦 Packages
This monorepo contains four main packages:
| Package | Description | Status |
|---------|-------------|--------|
| [@ai-assistant/core](./packages/core) | Core agent engine, tools, and integrations | ✅ Stable |
| [@ai-assistant/server](./packages/server) | HTTP/WebSocket server with REST API | ✅ Stable |
| [@ai-assistant/cli](./packages/cli) | Command-line interface | ✅ Stable |
| [@ai-assistant/web](./packages/web) | React-based web interface | ✅ Stable |
## 🏗️ Architecture
```mermaid
graph TD
Web[Web UI] --> Server
CLI[CLI] --> Server
Desktop[Desktop App] --> Server
Server --> Core[Core Engine]
Core --> Tools[Tool System]
Core --> LSP[Language Server]
Core --> MCP[Model Context Protocol]
Core --> Checkpoint[Checkpoint System]
```
### Technology Stack
- **Runtime**: Bun / Node.js
- **Language**: TypeScript
- **Server**: Hono + Bun WebSocket
- **Frontend**: React + Vite + Tailwind CSS
- **Desktop**: Tauri (Rust + WebView)
- **Testing**: Vitest
- **Package Manager**: pnpm (monorepo)
## 📖 Documentation
Detailed documentation is available in the [docs](./docs) directory:
- [Architecture Overview](./docs/design/architecture/gui-server-client.md)
- [API Reference](./docs/api/README.md)
- [Development Guide](./docs/development/README.md)
- [Configuration Guide](./docs/configuration/README.md)
## 🛠️ Development
### Common Commands
```bash ```bash
ai-assist ask "如何读取当前目录下的所有文件?" # Install dependencies
pnpm install
# Build all packages
pnpm build
# Run tests
pnpm test
pnpm test:coverage
# Linting
pnpm lint
# Type checking
pnpm typecheck
# Clean build artifacts
pnpm clean
``` ```
## 🎯 使用示例 ### Package-specific Development
### 文件操作 ```bash
``` # Work on a specific package
用户:读取 package.json 文件 pnpm --filter @ai-assistant/core dev
AI:正在读取 package.json... pnpm --filter @ai-assistant/server test
(显示文件内容) pnpm --filter @ai-assistant/web build
用户:修改版本号为 1.0.1
AI:确认要修改 package.json 吗? (y/n)
``` ```
### 代码分析 ## 🔧 Configuration
```
用户:帮我分析 src/index.ts 中的主要功能
AI:正在读取文件...
(分析代码结构,解释主要功能)
```
### 系统命令 ### Environment Variables
```
用户:查看当前目录的文件列表
AI:正在执行 ls -la...
(显示目录内容)
用户:安装 lodash 包
AI:确认要执行 npm install lodash 吗? (y/n)
```
## 🔧 配置 Create a `.env` file in the root directory:
### 环境变量
创建 `.env` 文件(参考 `.env.example`):
```env ```env
# Anthropic API Key (必需) # Required
ANTHROPIC_API_KEY=sk-ant-xxxxx ANTHROPIC_API_KEY=sk-ant-xxxxx
# 可选配置 # Optional
AI_MODEL=claude-sonnet-4-20250514 AI_MODEL=claude-sonnet-4-20250514
AI_MAX_TOKENS=4096 AI_MAX_TOKENS=4096
SERVER_PORT=3000
SERVER_HOST=localhost
``` ```
### 支持的 AI 模型 ### Supported Models
- `claude-sonnet-4-20250514` (默认)
- `claude-sonnet-4-20250514` (default)
- `claude-haiku-3-20251120` - `claude-haiku-3-20251120`
- 其他 Claude 模型 - Other Claude models
## 📁 项目结构 ## 🤝 Contributing
``` We welcome contributions! Please see our [Contributing Guide](./CONTRIBUTING.md) for details.
ai-terminal-assistant/
├── src/
│ ├── core/ # 核心代理逻辑
│ ├── tools/ # 工具函数
│ │ ├── bash.ts # Bash 命令工具
│ │ ├── file.ts # 文件操作工具
│ │ └── index.ts # 工具导出
│ ├── ui/ # 用户界面
│ ├── utils/ # 工具函数
│ └── index.ts # 主入口文件
├── dist/ # 编译输出
├── package.json
├── tsconfig.json
└── README.md
```
## 🛠️ 开发 1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
### 构建项目 ## 📄 License
```bash
npm run build
```
### 开发模式 This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.
```bash
npm run dev
```
### 代码检查 ## 🙏 Acknowledgments
```bash
npm run lint
```
## ⚠️ 安全注意事项 - Built with [Claude API](https://docs.anthropic.com/claude/reference/getting-started-with-the-api) by Anthropic
- Powered by [Bun](https://bun.sh) for fast JavaScript runtime
- UI components from [Tailwind CSS](https://tailwindcss.com)
- Desktop app built with [Tauri](https://tauri.app)
1. **API Key 安全**:不要将 `.env` 文件提交到版本控制 ## 📞 Support
2. **命令确认**:AI 在执行修改文件或运行系统命令前会请求确认
3. **权限管理**:确保 AI 助手只有必要的文件访问权限
## 📝 许可证 - 📧 Email: support@example.com
- 💬 Discord: [Join our community](https://discord.gg/example)
MIT License - 🐛 Issues: [GitHub Issues](https://github.com/username/repo/issues)
## 🤝 贡献
欢迎提交 Issue 和 Pull Request
## 🐛 问题反馈
如果您遇到任何问题,请:
1. 检查 API Key 是否正确配置
2. 确保有足够的 API 额度
3. 查看终端错误信息
4. 在 GitHub 上提交 Issue
## 📚 相关技术
- [Claude API](https://docs.anthropic.com/claude/reference/getting-started-with-the-api)
- [Node.js](https://nodejs.org/)
- [TypeScript](https://www.typescriptlang.org/)
- [Commander.js](https://github.com/tj/commander.js) - CLI 框架
- [Inquirer.js](https://github.com/SBoudrias/Inquirer.js) - 交互式命令行界面
--- ---
**提示**:AI 助手会尽力帮助您,但请始终审查它建议的代码更改和命令执行,特别是在生产环境中。 <div align="center">
Made with ❤️ by the AI Terminal Assistant Team
</div>
+321
View File
@@ -0,0 +1,321 @@
# @ai-assistant/cli
Command-line interface for AI Terminal Assistant - interact with AI directly from your terminal.
## 📦 Installation
```bash
# Global installation
pnpm add -g @ai-assistant/cli
# Or run directly with npx/bunx
npx @ai-assistant/cli
bunx @ai-assistant/cli
```
## 🌟 Features
- **Dual Modes** - Server mode and client attach mode
- **Interactive Chat** - Rich terminal UI with syntax highlighting
- **Streaming Responses** - Real-time AI responses
- **File Attachments** - Attach files to messages
- **Command History** - Navigate through previous commands
- **Auto-completion** - Tab completion for commands
- **Colored Output** - Beautiful terminal formatting
- **Session Management** - Persistent conversation history
## 🚀 Quick Start
### Server Mode
Start a local AI server:
```bash
# Start server on default port 3000
ai-assist serve
# Start on custom port
ai-assist serve --port 8080
# With specific model
ai-assist serve --model claude-haiku-3-20251120
# With verbose logging
ai-assist serve --verbose
```
### Client Mode
Attach to a running AI server:
```bash
# Attach to local server
ai-assist attach
# Attach to remote server
ai-assist attach https://ai-server.example.com
# Attach with authentication
ai-assist attach https://ai-server.example.com --token YOUR_TOKEN
# Attach to specific session
ai-assist attach --session my-session-id
```
## 📚 Commands
### Global Options
```bash
ai-assist [command] [options]
Options:
-h, --help Show help
-v, --version Show version
--config <path> Path to config file
--verbose Enable verbose logging
```
### Server Command
```bash
ai-assist serve [options]
Options:
-p, --port <port> Server port (default: 3000)
-h, --host <host> Server host (default: localhost)
--api-key <key> Anthropic API key (or use ANTHROPIC_API_KEY env)
--model <model> AI model to use
--max-tokens <n> Maximum response tokens
--no-auth Disable authentication
--cors-origin <origin> CORS allowed origins
```
### Attach Command
```bash
ai-assist attach [server-url] [options]
Arguments:
server-url Server URL (default: http://localhost:3000)
Options:
-s, --session <id> Session ID to attach to
-t, --token <token> Authentication token
--no-history Don't load session history
--stream Enable streaming mode
```
## ⌨️ Interactive Commands
Once connected, use these commands in the chat interface:
```
/help Show available commands
/clear Clear the screen
/history Show message history
/attach <file> Attach a file to the next message
/model <name> Switch AI model
/session new Start a new session
/session list List available sessions
/session switch <id> Switch to another session
/export <file> Export conversation to file
/quit Exit the CLI
```
## 🎨 Terminal UI Features
### Message Display
- **User messages** - Displayed with `>` prefix in cyan
- **AI responses** - Formatted with syntax highlighting
- **Code blocks** - Highlighted based on language
- **Markdown** - Rendered with terminal formatting
- **Progress indicators** - Animated spinners during processing
### Keyboard Shortcuts
- `↑/↓` - Navigate message history
- `Tab` - Auto-complete commands
- `Ctrl+C` - Cancel current operation
- `Ctrl+D` - Exit (same as /quit)
- `Ctrl+L` - Clear screen (same as /clear)
- `PgUp/PgDn` - Scroll through long responses
## 🔧 Configuration
### Configuration File
Create `~/.ai-assistant/config.json`:
```json
{
"defaultServer": "http://localhost:3000",
"apiKey": "sk-ant-xxxxx",
"model": "claude-sonnet-4-20250514",
"theme": "dark",
"editor": "vim",
"history": {
"enabled": true,
"maxSize": 1000
},
"display": {
"showTimestamps": true,
"syntax_highlighting": true,
"word_wrap": true,
"max_width": 120
}
}
```
### Environment Variables
```bash
# API Configuration
export ANTHROPIC_API_KEY=sk-ant-xxxxx
export AI_MODEL=claude-sonnet-4-20250514
# CLI Configuration
export AI_CLI_SERVER=http://localhost:3000
export AI_CLI_SESSION=my-session
export AI_CLI_TOKEN=auth-token
# Display Configuration
export AI_CLI_COLOR=true
export AI_CLI_EDITOR=vim
```
## 🔌 Scripting and Automation
### Pipe Input
```bash
# Send a single message
echo "What is TypeScript?" | ai-assist attach
# Process a file
cat code.ts | ai-assist attach --message "Review this code"
# Chain with other commands
git diff | ai-assist attach --message "Explain these changes"
```
### Script Mode
```bash
#!/bin/bash
# Create a script for batch processing
ai-assist attach <<EOF
/session new
Analyze the following log file
/attach /var/log/application.log
What are the main errors?
/export analysis.md
/quit
EOF
```
### JSON Output
```bash
# Get JSON response for parsing
ai-assist attach --json --message "List TypeScript features" | jq '.response.content'
```
## 🧪 Testing
```bash
# Run tests
pnpm test
# Run with coverage
pnpm test:coverage
# Run specific test suite
pnpm test -- cli.test.ts
```
## 🚀 Advanced Usage
### Custom Tools
Register custom tools in your config:
```json
{
"tools": [
{
"name": "deploy",
"command": "kubectl apply -f",
"description": "Deploy to Kubernetes"
}
]
}
```
### Plugins
Install and use CLI plugins:
```bash
# Install a plugin
ai-assist plugin install @ai-assistant/plugin-git
# List plugins
ai-assist plugin list
# Use plugin command
ai-assist git analyze
```
## 🐛 Troubleshooting
### Connection Issues
```bash
# Test server connection
ai-assist test-connection http://localhost:3000
# Check server status
curl http://localhost:3000/api/health
```
### Debug Mode
```bash
# Enable debug logging
DEBUG=* ai-assist attach
# Save debug log
ai-assist attach --debug 2> debug.log
```
### Common Issues
1. **"Cannot connect to server"**
- Check if server is running
- Verify server URL and port
- Check firewall settings
2. **"Authentication failed"**
- Verify API key is set
- Check token expiration
- Ensure server auth is configured
3. **"Session not found"**
- Session may have expired
- Use `/session list` to see available sessions
- Create new session with `/session new`
## 🤝 Contributing
Contributions are welcome! See the main repository's contributing guide.
## 📄 License
MIT License - see [LICENSE](../../LICENSE) for details.
## 🔗 Links
- [Main Repository](https://github.com/username/ai-terminal-assistant)
- [Documentation](https://docs.example.com/cli)
- [Issue Tracker](https://github.com/username/ai-terminal-assistant/issues)
+245
View File
@@ -0,0 +1,245 @@
# @ai-assistant/core
Core engine package for AI Terminal Assistant - provides the AI agent, tools, and integrations.
## 📦 Installation
```bash
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
```typescript
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
```typescript
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
```typescript
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
```typescript
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
```typescript
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
```typescript
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
```typescript
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
```typescript
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
```typescript
interface Editor {
edit(path: string, content: string | EditParams): Promise<void>;
validate(content: string): boolean;
preview(path: string, content: string): string;
}
```
## 🧪 Testing
```bash
# 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](../../LICENSE) for details.
## 🔗 Links
- [Main Repository](https://github.com/username/ai-terminal-assistant)
- [API Documentation](https://docs.example.com/core)
- [Issue Tracker](https://github.com/username/ai-terminal-assistant/issues)
+436
View File
@@ -0,0 +1,436 @@
# @ai-assistant/desktop
Native desktop application for AI Terminal Assistant - built with Tauri for cross-platform support.
## 📦 Installation
```bash
# Install dependencies
pnpm install
# Development
pnpm dev
# Build for current platform
pnpm build
# Build for all platforms
pnpm build:all
```
## 🌟 Features
- **Native Performance** - Built with Rust and Tauri for speed
- **Cross-Platform** - Windows, macOS, and Linux support
- **Small Bundle Size** - ~10MB installer, ~30MB installed
- **System Integration** - Native menus, notifications, and tray
- **Secure by Default** - Sandboxed with minimal permissions
- **Auto Updates** - Built-in update mechanism
- **Local Storage** - SQLite for offline data
- **WebView Based** - Modern web UI with native wrapper
- **Global Shortcuts** - System-wide keyboard shortcuts
- **File System Access** - Native file dialogs and operations
## 🏗️ Architecture
```
src-tauri/
├── src/
│ ├── main.rs # Main entry point
│ ├── app.rs # Application setup
│ ├── commands/ # Tauri commands
│ │ ├── chat.rs # Chat operations
│ │ ├── file.rs # File operations
│ │ ├── system.rs # System integration
│ │ └── window.rs # Window management
│ ├── menu.rs # Native menu setup
│ ├── tray.rs # System tray
│ ├── updater.rs # Auto-updater logic
│ ├── store.rs # Local data storage
│ └── utils/ # Utility functions
├── Cargo.toml # Rust dependencies
├── tauri.conf.json # Tauri configuration
└── icons/ # App icons
src/
├── App.tsx # React app entry
├── components/ # UI components (shared with web)
├── hooks/ # Custom hooks
├── services/ # Desktop-specific services
│ ├── ipc.ts # Tauri IPC communication
│ ├── storage.ts # Local storage
│ └── shortcuts.ts # Keyboard shortcuts
└── styles/ # Desktop-specific styles
```
## 🚀 Quick Start
### Prerequisites
- **Node.js** 18+ and pnpm
- **Rust** 1.70+ (install from [rustup.rs](https://rustup.rs))
- **Platform Tools**:
- **Windows**: Visual Studio C++ Build Tools
- **macOS**: Xcode Command Line Tools
- **Linux**: `build-essential`, `libwebkit2gtk-4.0-dev`, `libssl-dev`
### Development Setup
```bash
# Clone repository
git clone <repository-url>
cd ai-terminal-assistant/packages/desktop
# Install dependencies
pnpm install
# Start development server
pnpm dev
# App will open automatically with hot reload enabled
```
### Building for Production
```bash
# Build for current platform
pnpm build
# Build for specific platform
pnpm build:windows
pnpm build:mac
pnpm build:linux
# Build universal binary for macOS
pnpm build:mac-universal
# Build and sign (requires certificates)
pnpm build:signed
```
## 🖥️ Platform Features
### Windows
- **Installer Types**: MSI, NSIS, Portable
- **Auto-start** on system boot
- **Windows Store** distribution ready
- **Native notifications**
- **Jump list** integration
### macOS
- **Formats**: DMG, App Bundle
- **Code signing** and notarization
- **macOS App Store** ready
- **Touch Bar** support
- **Native menu bar**
### Linux
- **Packages**: AppImage, Deb, RPM
- **System tray** support
- **Desktop entry** creation
- **Snap/Flatpak** ready
- **Wayland/X11** compatible
## ⚙️ Configuration
### Tauri Configuration
`src-tauri/tauri.conf.json`:
```json
{
"package": {
"productName": "AI Terminal Assistant",
"version": "1.0.0"
},
"tauri": {
"allowlist": {
"all": false,
"shell": {
"execute": true,
"open": true
},
"fs": {
"all": true,
"scope": ["$HOME/**", "$RESOURCE/**"]
},
"http": {
"all": true,
"scope": ["http://localhost/*", "https://api.anthropic.com/*"]
},
"notification": {
"all": true
},
"globalShortcut": {
"all": true
}
},
"windows": [{
"title": "AI Terminal Assistant",
"width": 1200,
"height": 800,
"resizable": true,
"fullscreen": false
}],
"systemTray": {
"iconPath": "icons/icon.png",
"menuOnLeftClick": false
},
"updater": {
"active": true,
"endpoints": ["https://updates.example.com/check"]
}
}
}
```
## 🔌 Tauri Commands
### IPC Communication
```typescript
// Frontend (TypeScript)
import { invoke } from '@tauri-apps/api/tauri';
// Call Rust command
const result = await invoke('send_message', {
message: 'Hello from frontend'
});
// Listen to events
import { listen } from '@tauri-apps/api/event';
const unlisten = await listen('chat-update', (event) => {
console.log('New message:', event.payload);
});
```
```rust
// Backend (Rust)
#[tauri::command]
fn send_message(message: String) -> Result<String, String> {
// Process message
Ok(format!("Received: {}", message))
}
// Emit events
app.emit_all("chat-update", Payload {
message: "New update"
}).unwrap();
```
## 🎨 Native Features
### System Tray
```typescript
import { createTray } from './services/tray';
const tray = await createTray({
icon: '/icons/tray.png',
menu: [
{ label: 'Show', action: () => showWindow() },
{ label: 'Hide', action: () => hideWindow() },
{ separator: true },
{ label: 'Quit', action: () => app.quit() }
]
});
```
### Global Shortcuts
```typescript
import { register } from '@tauri-apps/api/globalShortcut';
// Register global hotkey
await register('CommandOrControl+Shift+A', () => {
console.log('Shortcut triggered!');
window.show();
});
```
### File Operations
```typescript
import { open, save } from '@tauri-apps/api/dialog';
import { readTextFile, writeFile } from '@tauri-apps/api/fs';
// Open file dialog
const selected = await open({
multiple: false,
filters: [{
name: 'Text',
extensions: ['txt', 'md']
}]
});
// Read file
const content = await readTextFile(selected);
// Save file dialog
const savePath = await save({
filters: [{ name: 'Text', extensions: ['txt'] }]
});
await writeFile(savePath, 'content');
```
### Notifications
```typescript
import { sendNotification } from '@tauri-apps/api/notification';
await sendNotification({
title: 'AI Assistant',
body: 'Task completed successfully!',
icon: '/icons/icon.png'
});
```
## 🔐 Security
### Permissions
- Minimal permission model
- Scoped file system access
- Controlled shell execution
- CSP headers enforced
### Code Signing
```bash
# macOS
codesign --deep --force --verify --verbose \
--sign "Developer ID Application: Your Name" \
target/release/bundle/osx/AI\ Terminal\ Assistant.app
# Windows (using SignTool)
signtool sign /a /tr http://timestamp.digicert.com \
/td SHA256 /fd SHA256 \
target/release/bundle/msi/AI_Terminal_Assistant.msi
```
## 🚢 Distribution
### Auto Updates
```rust
// src-tauri/src/updater.rs
use tauri::updater::builder::UpdateBuilder;
pub fn check_for_updates(app: &tauri::App) {
let update = UpdateBuilder::new()
.current_version(&app.package_info().version)
.url("https://updates.example.com/check")
.build()
.unwrap();
if update.should_update {
update.download_and_install().unwrap();
}
}
```
### GitHub Releases
```yaml
# .github/workflows/release.yml
name: Release
on:
push:
tags: ['v*']
jobs:
release:
strategy:
matrix:
platform: [macos-latest, ubuntu-latest, windows-latest]
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v3
- uses: tauri-apps/tauri-action@v0
with:
tagName: v__VERSION__
releaseName: 'v__VERSION__'
releaseBody: 'See CHANGELOG.md'
releaseDraft: true
prerelease: false
```
## 🧪 Testing
```bash
# Unit tests (Rust)
cd src-tauri
cargo test
# Integration tests
pnpm test:integration
# E2E tests with WebDriver
pnpm test:e2e
```
## 📊 Performance
### Optimization Tips
1. **Lazy Loading** - Load features on demand
2. **IPC Batching** - Batch multiple commands
3. **Asset Optimization** - Compress images/fonts
4. **Memory Management** - Clean up listeners
5. **Background Tasks** - Use Web Workers
### Benchmarks
| Metric | Value |
|--------|-------|
| Startup Time | < 500ms |
| Memory Usage | ~50MB idle |
| Bundle Size | ~10MB compressed |
| CPU Usage | < 5% idle |
## 🐛 Debugging
### Development Tools
```bash
# Enable dev tools
pnpm dev -- --features devtools
# Rust debugging
RUST_LOG=debug pnpm dev
# WebView debugging
# Press F12 in the app window
```
### Logging
```rust
// Rust logging
use log::{info, error};
info!("Application started");
error!("Failed to load: {}", error);
```
```typescript
// Frontend logging
import { info, error } from '@tauri-apps/api/log';
await info('Application started');
await error(`Failed to load: ${error}`);
```
## 🤝 Contributing
See the main repository's contributing guide for details.
## 📄 License
MIT License - see [LICENSE](../../LICENSE) for details.
## 🔗 Links
- [Main Repository](https://github.com/username/ai-terminal-assistant)
- [Tauri Documentation](https://tauri.app/v1/guides/)
- [Release Downloads](https://github.com/username/ai-terminal-assistant/releases)
+354
View File
@@ -0,0 +1,354 @@
# @ai-assistant/server
HTTP/WebSocket server for AI Terminal Assistant - provides REST API, WebSocket, and SSE endpoints.
## 📦 Installation
```bash
pnpm add @ai-assistant/server
```
## 🌟 Features
- **REST API** - Full CRUD operations for sessions and tools
- **WebSocket** - Real-time bidirectional communication
- **Server-Sent Events** - Streaming status updates
- **Authentication** - Token-based auth for non-localhost
- **Session Management** - Persistent session handling
- **CORS Support** - Configurable cross-origin access
- **Built with Hono** - Lightweight, fast web framework
- **Bun Runtime** - Native WebSocket and performance
## 🏗️ Architecture
```
src/
├── index.ts # Main server setup with Hono
├── routes/
│ ├── sessions.ts # Session management endpoints
│ ├── tools.ts # Tool execution endpoints
│ ├── config.ts # Configuration endpoints
│ └── health.ts # Health check endpoint
├── ws.ts # WebSocket handler
├── sse.ts # Server-Sent Events handler
├── agent/
│ ├── adapter.ts # Core agent adapter
│ └── session.ts # Session management
├── auth/
│ ├── token.ts # Token generation/validation
│ └── middleware.ts # Auth middleware
├── middleware/
│ ├── cors.ts # CORS configuration
│ ├── error.ts # Error handling
│ └── logging.ts # Request logging
└── types/
└── index.ts # TypeScript definitions
```
## 🚀 Quick Start
### Basic Server Setup
```typescript
import { createServer } from '@ai-assistant/server';
const server = createServer({
port: 3000,
host: 'localhost',
apiKey: process.env.ANTHROPIC_API_KEY
});
await server.start();
console.log('Server running on http://localhost:3000');
```
### Standalone Usage
```bash
# Development mode with hot reload
pnpm start:dev
# Production mode
pnpm start
# With custom configuration
ANTHROPIC_API_KEY=sk-ant-xxx SERVER_PORT=8080 pnpm start
```
## 📡 API Endpoints
### REST API
#### Sessions
```typescript
// Create session
POST /api/sessions
Response: { id: string, status: 'idle' | 'busy', createdAt: string }
// Get session
GET /api/sessions/:id
Response: { id: string, status: string, messages: Message[] }
// List sessions
GET /api/sessions
Response: Session[]
// Delete session
DELETE /api/sessions/:id
Response: { success: boolean }
```
#### Tools
```typescript
// List available tools
GET /api/tools
Response: Tool[]
// Execute tool
POST /api/tools/:name/execute
Body: { params: any, sessionId?: string }
Response: { result: any }
```
#### Configuration
```typescript
// Get configuration
GET /api/config
Response: { model: string, maxTokens: number, ... }
// Update configuration
PUT /api/config
Body: { model?: string, maxTokens?: number, ... }
Response: { success: boolean, config: Config }
```
### WebSocket Protocol
```typescript
// Connect
ws://localhost:3000/api/ws/:sessionId
// Client → Server Messages
{
type: 'message',
payload: {
content: string,
attachments?: Attachment[]
}
}
// Server → Client Messages
{
type: 'chunk' | 'done' | 'error' | 'status',
payload: {
content?: string, // For chunk
response?: Message, // For done
error?: string, // For error
status?: string // For status
}
}
```
### Server-Sent Events
```typescript
// Connect for status updates
GET /api/sse/:sessionId
Accept: text/event-stream
// Event format
event: status
data: { "status": "processing", "progress": 0.5 }
event: complete
data: { "result": "Task completed" }
```
## 🔧 Configuration
### Environment Variables
```env
# Required
ANTHROPIC_API_KEY=sk-ant-xxxxx
# Optional
SERVER_PORT=3000
SERVER_HOST=localhost
SERVER_CORS_ORIGIN=http://localhost:5173
SERVER_AUTH_ENABLED=auto
SERVER_LOG_LEVEL=info
AI_MODEL=claude-sonnet-4-20250514
AI_MAX_TOKENS=4096
```
### Programmatic Configuration
```typescript
interface ServerConfig {
port?: number; // Server port (default: 3000)
host?: string; // Server host (default: localhost)
apiKey: string; // Anthropic API key
cors?: {
origin: string | string[];
credentials?: boolean;
};
auth?: {
enabled: boolean | 'auto'; // Auto enables for non-localhost
tokenSecret?: string;
};
agent?: {
model?: string;
maxTokens?: number;
temperature?: number;
};
logging?: {
level: 'debug' | 'info' | 'warn' | 'error';
};
}
```
## 🔐 Authentication
The server automatically enables token authentication when accessed from non-localhost addresses:
```typescript
// Generate token
POST /api/auth/token
Body: { password?: string }
Response: { token: string, expiresIn: number }
// Use token in requests
Authorization: Bearer <token>
// Or in WebSocket
ws://server/api/ws/:sessionId?token=<token>
```
## 🧪 Testing
```bash
# Run tests
pnpm test
# Run with coverage
pnpm test:coverage
# E2E tests
pnpm test:e2e
```
### Test Examples
```typescript
import { testClient } from '@ai-assistant/server/test';
describe('Server API', () => {
const client = testClient({ port: 3001 });
beforeAll(() => client.start());
afterAll(() => client.stop());
test('create session', async () => {
const session = await client.post('/api/sessions');
expect(session.id).toBeDefined();
expect(session.status).toBe('idle');
});
test('websocket chat', async () => {
const ws = client.ws('/api/ws/test-session');
ws.send({ type: 'message', payload: { content: 'Hello' } });
const response = await ws.waitFor('done');
expect(response.payload.response).toBeDefined();
});
});
```
## 🔌 Integration Examples
### With Express
```typescript
import express from 'express';
import { createMiddleware } from '@ai-assistant/server';
const app = express();
app.use('/ai', createMiddleware({
apiKey: process.env.ANTHROPIC_API_KEY
}));
app.listen(3000);
```
### With Next.js
```typescript
// app/api/ai/[...path]/route.ts
import { handleRequest } from '@ai-assistant/server/next';
export const { GET, POST, PUT, DELETE } = handleRequest({
apiKey: process.env.ANTHROPIC_API_KEY
});
```
## 📊 Monitoring
### Health Check
```bash
curl http://localhost:3000/api/health
# Response: { status: 'healthy', uptime: 123456, sessions: 5 }
```
### Metrics Endpoint
```bash
curl http://localhost:3000/api/metrics
# Response: Prometheus-formatted metrics
```
## 🚀 Deployment
### Docker
```dockerfile
FROM oven/bun:1.0
WORKDIR /app
COPY package*.json ./
RUN bun install
COPY . .
EXPOSE 3000
CMD ["bun", "run", "start"]
```
### PM2
```json
{
"apps": [{
"name": "ai-server",
"script": "bun",
"args": "run start",
"env": {
"SERVER_PORT": 3000,
"ANTHROPIC_API_KEY": "sk-ant-xxx"
}
}]
}
```
## 🤝 Contributing
Contributions are welcome! Please follow the contribution guidelines in the main repository.
## 📄 License
MIT License - see [LICENSE](../../LICENSE) for details.
## 🔗 Links
- [Main Repository](https://github.com/username/ai-terminal-assistant)
- [API Documentation](https://docs.example.com/server)
- [OpenAPI Spec](https://api.example.com/openapi.json)
+366
View File
@@ -0,0 +1,366 @@
# @ai-assistant/web
Modern web interface for AI Terminal Assistant - built with React, Vite, and Tailwind CSS.
## 📦 Installation
```bash
# Install dependencies
pnpm install
# Start development server
pnpm dev
# Build for production
pnpm build
```
## 🌟 Features
- **Modern UI** - Clean, responsive interface with dark/light themes
- **Real-time Chat** - WebSocket-based instant messaging
- **Code Editor** - Syntax highlighting with Monaco Editor
- **File Browser** - Browse and edit project files
- **Terminal Integration** - Embedded terminal for command execution
- **Markdown Rendering** - Rich text formatting for AI responses
- **PWA Support** - Install as desktop/mobile app
- **Mobile Responsive** - Optimized for all screen sizes
- **Keyboard Shortcuts** - Efficient navigation and actions
## 🏗️ Architecture
```
src/
├── components/
│ ├── Chat/ # Chat interface components
│ │ ├── ChatWindow.tsx
│ │ ├── MessageList.tsx
│ │ ├── MessageInput.tsx
│ │ └── CodeBlock.tsx
│ ├── Editor/ # Code editor components
│ │ ├── MonacoEditor.tsx
│ │ └── EditorToolbar.tsx
│ ├── FileBrowser/ # File navigation
│ │ ├── FileTree.tsx
│ │ └── FilePreview.tsx
│ ├── Terminal/ # Terminal emulator
│ │ └── XTerminal.tsx
│ ├── Layout/ # Layout components
│ │ ├── Sidebar.tsx
│ │ ├── Header.tsx
│ │ └── Tabs.tsx
│ └── Common/ # Shared components
│ ├── Button.tsx
│ ├── Modal.tsx
│ └── Loading.tsx
├── hooks/ # Custom React hooks
│ ├── useChat.ts
│ ├── useWebSocket.ts
│ ├── useTheme.ts
│ └── useKeyboard.ts
├── services/ # API and service layer
│ ├── api.ts
│ ├── websocket.ts
│ └── storage.ts
├── store/ # State management
│ ├── chat.store.ts
│ ├── editor.store.ts
│ └── settings.store.ts
├── styles/ # Global styles
│ └── index.css
├── types/ # TypeScript definitions
├── utils/ # Utility functions
├── App.tsx # Main app component
└── main.tsx # Entry point
```
## 🚀 Quick Start
### Development
```bash
# Start development server
pnpm dev
# The app will be available at http://localhost:5173
# Hot module replacement is enabled for instant updates
```
### Production Build
```bash
# Create optimized build
pnpm build
# Preview production build
pnpm preview
# Build output in dist/ directory
```
## 🎨 User Interface
### Main Features
#### Chat Interface
- **Message History** - Scrollable chat with persistent history
- **Code Highlighting** - Syntax highlighting for code blocks
- **File Attachments** - Drag & drop file support
- **Message Actions** - Copy, edit, regenerate responses
- **Streaming Responses** - Real-time AI response streaming
#### Code Editor
- **Monaco Editor** - VS Code's editor engine
- **Multi-file Tabs** - Work with multiple files
- **Syntax Highlighting** - 100+ language support
- **IntelliSense** - Code completion and hints
- **Diff View** - Side-by-side code comparison
#### File Browser
- **Tree View** - Hierarchical file structure
- **Quick Actions** - Create, rename, delete files
- **Search** - Fast file search with fuzzy matching
- **Preview** - Quick file preview without opening
- **Context Menu** - Right-click actions
#### Terminal
- **XTerm.js** - Full terminal emulation
- **Command History** - Navigate previous commands
- **Copy/Paste** - Standard clipboard operations
- **Themes** - Multiple color schemes
## 🎯 Component Examples
### Using the Chat Component
```tsx
import { Chat } from '@ai-assistant/web/components';
function App() {
return (
<Chat
serverUrl="http://localhost:3000"
sessionId="my-session"
onMessage={(message) => console.log('New message:', message)}
theme="dark"
/>
);
}
```
### Custom Hook Usage
```tsx
import { useChat } from '@ai-assistant/web/hooks';
function MyComponent() {
const { messages, sendMessage, isLoading } = useChat({
serverUrl: 'http://localhost:3000',
sessionId: 'my-session'
});
return (
<div>
{messages.map(msg => (
<div key={msg.id}>{msg.content}</div>
))}
<button onClick={() => sendMessage('Hello AI!')}>
Send Message
</button>
</div>
);
}
```
## ⚙️ Configuration
### Environment Variables
Create `.env` file:
```env
# API Configuration
VITE_API_URL=http://localhost:3000
VITE_WS_URL=ws://localhost:3000
VITE_AUTH_TOKEN=your-token-here
# Feature Flags
VITE_ENABLE_TERMINAL=true
VITE_ENABLE_FILE_BROWSER=true
VITE_ENABLE_CODE_EDITOR=true
# Theme
VITE_DEFAULT_THEME=dark
```
### Build Configuration
`vite.config.ts`:
```typescript
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
proxy: {
'/api': 'http://localhost:3000'
}
},
build: {
outDir: 'dist',
sourcemap: true,
minify: 'esbuild'
}
});
```
## 🎹 Keyboard Shortcuts
| Shortcut | Action |
|----------|--------|
| `Ctrl/Cmd + Enter` | Send message |
| `Ctrl/Cmd + K` | Clear chat |
| `Ctrl/Cmd + /` | Toggle sidebar |
| `Ctrl/Cmd + ,` | Open settings |
| `Ctrl/Cmd + Shift + P` | Command palette |
| `Ctrl/Cmd + B` | Toggle file browser |
| `Ctrl/Cmd + J` | Toggle terminal |
| `Esc` | Close modal/popup |
## 📱 Progressive Web App
The app can be installed as a PWA:
1. Open in Chrome/Edge
2. Click install icon in address bar
3. Or use browser menu: "Install App"
Features:
- Offline support with service worker
- Desktop/mobile app experience
- Push notifications (coming soon)
- Background sync
## 🧪 Testing
```bash
# Run unit tests
pnpm test
# Run with coverage
pnpm test:coverage
# Run E2E tests
pnpm test:e2e
# Component testing
pnpm test:components
```
### Testing Examples
```tsx
import { render, screen } from '@testing-library/react';
import { Chat } from './Chat';
test('renders chat interface', () => {
render(<Chat serverUrl="http://localhost:3000" />);
expect(screen.getByPlaceholderText('Type a message...')).toBeInTheDocument();
});
```
## 🎨 Theming
### Custom Theme
```css
/* src/styles/themes/custom.css */
:root[data-theme="custom"] {
--primary: #6366f1;
--background: #0f172a;
--foreground: #f8fafc;
--border: #334155;
--accent: #8b5cf6;
}
```
### Apply Theme
```tsx
import { useTheme } from '@ai-assistant/web/hooks';
function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme('custom')}>
Use Custom Theme
</button>
);
}
```
## 📊 Performance
### Optimization Tips
1. **Code Splitting** - Routes are lazy loaded
2. **Image Optimization** - WebP with fallbacks
3. **Bundle Size** - Tree shaking enabled
4. **Caching** - Service worker caching
5. **Virtual Scrolling** - For long lists
### Bundle Analysis
```bash
# Analyze bundle size
pnpm build:analyze
# Opens visualization in browser
```
## 🚀 Deployment
### Vercel
```bash
# Deploy to Vercel
vercel deploy --prod
```
### Docker
```dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
```
### Static Hosting
Build output in `dist/` can be served by any static host:
- Netlify
- GitHub Pages
- CloudFlare Pages
- AWS S3 + CloudFront
## 🤝 Contributing
See the main repository's contributing guide for details.
## 📄 License
MIT License - see [LICENSE](../../LICENSE) for details.
## 🔗 Links
- [Main Repository](https://github.com/username/ai-terminal-assistant)
- [Component Storybook](https://storybook.example.com)
- [Design System](https://design.example.com)