diff --git a/README.md b/README.md index 0f23efc..df7c9ab 100644 --- a/README.md +++ b/README.md @@ -1,180 +1,224 @@ # AI Terminal Assistant -**็”ฑ kurihada ๅผ€ๅ‘** +
+

๐Ÿค– A powerful terminal-based AI coding assistant powered by Claude API

+

+ Features โ€ข + Quick Start โ€ข + Documentation โ€ข + Packages +

+

+ License + Node + pnpm +

+
-ไธ€ไธช่ฟ่กŒๅœจ็ปˆ็ซฏไธญ็š„ 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 ไบคไบ’ -- ๐Ÿ”ง **ๅผบๅคง็š„ๅทฅๅ…ท้›†**๏ผš - - ๆ–‡ไปถ่ฏปๅ†™ๆ“ไฝœ - - Bash ๅ‘ฝไปคๆ‰ง่กŒ - - ็›ฎๅฝ•ๅˆ—่กจๅ’Œๆ–‡ไปถๆœ็ดข - - ไปฃ็ ๅˆ†ๆžๅ’Œๅปบ่ฎฎ -- ๐Ÿ›ก๏ธ **ๅฎ‰ๅ…จ็ฌฌไธ€**๏ผšๅœจๆ‰ง่กŒๅฏ่ƒฝๆœ‰้ฃŽ้™ฉ็š„ๅ‘ฝไปคๅ‰ไผš่ฏทๆฑ‚็กฎ่ฎค -- ๐Ÿ’ฌ **ไธค็งๆจกๅผ**๏ผš - - ไบคไบ’ๆจกๅผ๏ผšๆŒ็ปญๅฏน่ฏ - - ๅ•ๆฌกๆ้—ฎๆจกๅผ๏ผšๅฟซ้€Ÿ่Žทๅ–็ญ”ๆกˆ -- โš™๏ธ **ๅฏ้…็ฝฎ**๏ผšๆ”ฏๆŒๅคš็ง AI ๆจกๅž‹ๅ’Œๅ‚ๆ•ฐ้…็ฝฎ +## โœจ Features -## ๐Ÿ“ฆ ๅฎ‰่ฃ… +### 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 -### ๅ‰ๆๆกไปถ -- Node.js 18+ +### User Interfaces +- ๐Ÿ–ฅ๏ธ **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 -### ๅ…จๅฑ€ๅฎ‰่ฃ… -```bash -npm install -g . -``` +### Installation -### ๆœฌๅœฐๅผ€ๅ‘ ```bash -# ๅ…‹้š†้กน็›ฎ -git clone +# Clone the repository +git clone cd ai-terminal-assistant -# ๅฎ‰่ฃ…ไพ่ต– -npm install +# Install dependencies +pnpm install -# ๆž„ๅปบ้กน็›ฎ -npm run build +# Set up environment variables +cp .env.example .env +# Edit .env and add your ANTHROPIC_API_KEY -# ้“พๆŽฅๅˆฐๅ…จๅฑ€ -npm link +# Build all packages +pnpm build ``` -## ๐Ÿš€ ๅฟซ้€Ÿๅผ€ๅง‹ +### Running the Application -### 1. ๅˆๅง‹ๅŒ–้…็ฝฎ +#### Option 1: Web Interface ```bash -ai-assist init -``` -ๆŒ‰็…งๆ็คบ่ฎพ็ฝฎๆ‚จ็š„ Anthropic API Keyใ€‚ +# Start the server +pnpm server:dev -### 2. ๅฏๅŠจไบคไบ’ๆจกๅผ +# In another terminal, start the web UI +pnpm web:dev + +# Open http://localhost:5173 in your browser +``` + +#### Option 2: CLI Mode ```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 -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 -### ๆ–‡ไปถๆ“ไฝœ -``` -็”จๆˆท๏ผš่ฏปๅ– package.json ๆ–‡ไปถ -AI๏ผšๆญฃๅœจ่ฏปๅ– package.json... -๏ผˆๆ˜พ็คบๆ–‡ไปถๅ†…ๅฎน๏ผ‰ -็”จๆˆท๏ผšไฟฎๆ”น็‰ˆๆœฌๅทไธบ 1.0.1 -AI๏ผš็กฎ่ฎค่ฆไฟฎๆ”น package.json ๅ—๏ผŸ (y/n) +```bash +# Work on a specific package +pnpm --filter @ai-assistant/core dev +pnpm --filter @ai-assistant/server test +pnpm --filter @ai-assistant/web build ``` -### ไปฃ็ ๅˆ†ๆž -``` -็”จๆˆท๏ผšๅธฎๆˆ‘ๅˆ†ๆž src/index.ts ไธญ็š„ไธป่ฆๅŠŸ่ƒฝ -AI๏ผšๆญฃๅœจ่ฏปๅ–ๆ–‡ไปถ... -๏ผˆๅˆ†ๆžไปฃ็ ็ป“ๆž„๏ผŒ่งฃ้‡Šไธป่ฆๅŠŸ่ƒฝ๏ผ‰ -``` +## ๐Ÿ”ง Configuration -### ็ณป็ปŸๅ‘ฝไปค -``` -็”จๆˆท๏ผšๆŸฅ็œ‹ๅฝ“ๅ‰็›ฎๅฝ•็š„ๆ–‡ไปถๅˆ—่กจ -AI๏ผšๆญฃๅœจๆ‰ง่กŒ ls -la... -๏ผˆๆ˜พ็คบ็›ฎๅฝ•ๅ†…ๅฎน๏ผ‰ -็”จๆˆท๏ผšๅฎ‰่ฃ… lodash ๅŒ… -AI๏ผš็กฎ่ฎค่ฆๆ‰ง่กŒ npm install lodash ๅ—๏ผŸ (y/n) -``` +### Environment Variables -## ๐Ÿ”ง ้…็ฝฎ - -### ็Žฏๅขƒๅ˜้‡ -ๅˆ›ๅปบ `.env` ๆ–‡ไปถ๏ผˆๅ‚่€ƒ `.env.example`๏ผ‰๏ผš +Create a `.env` file in the root directory: ```env -# Anthropic API Key (ๅฟ…้œ€) +# Required ANTHROPIC_API_KEY=sk-ant-xxxxx -# ๅฏ้€‰้…็ฝฎ +# Optional AI_MODEL=claude-sonnet-4-20250514 AI_MAX_TOKENS=4096 +SERVER_PORT=3000 +SERVER_HOST=localhost ``` -### ๆ”ฏๆŒ็š„ AI ๆจกๅž‹ -- `claude-sonnet-4-20250514` (้ป˜่ฎค) +### Supported Models + +- `claude-sonnet-4-20250514` (default) - `claude-haiku-3-20251120` -- ๅ…ถไป– Claude ๆจกๅž‹ +- Other Claude models -## ๐Ÿ“ ้กน็›ฎ็ป“ๆž„ +## ๐Ÿค Contributing -``` -ai-terminal-assistant/ -โ”œโ”€โ”€ src/ -โ”‚ โ”œโ”€โ”€ core/ # ๆ ธๅฟƒไปฃ็†้€ป่พ‘ -โ”‚ โ”œโ”€โ”€ tools/ # ๅทฅๅ…ทๅ‡ฝๆ•ฐ -โ”‚ โ”‚ โ”œโ”€โ”€ bash.ts # Bash ๅ‘ฝไปคๅทฅๅ…ท -โ”‚ โ”‚ โ”œโ”€โ”€ file.ts # ๆ–‡ไปถๆ“ไฝœๅทฅๅ…ท -โ”‚ โ”‚ โ””โ”€โ”€ index.ts # ๅทฅๅ…ทๅฏผๅ‡บ -โ”‚ โ”œโ”€โ”€ ui/ # ็”จๆˆท็•Œ้ข -โ”‚ โ”œโ”€โ”€ utils/ # ๅทฅๅ…ทๅ‡ฝๆ•ฐ -โ”‚ โ””โ”€โ”€ index.ts # ไธปๅ…ฅๅฃๆ–‡ไปถ -โ”œโ”€โ”€ dist/ # ็ผ–่ฏ‘่พ“ๅ‡บ -โ”œโ”€โ”€ package.json -โ”œโ”€โ”€ tsconfig.json -โ””โ”€โ”€ README.md -``` +We welcome contributions! Please see our [Contributing Guide](./CONTRIBUTING.md) for details. -## ๐Ÿ› ๏ธ ๅผ€ๅ‘ +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 -### ๆž„ๅปบ้กน็›ฎ -```bash -npm run build -``` +## ๐Ÿ“„ License -### ๅผ€ๅ‘ๆจกๅผ -```bash -npm run dev -``` +This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details. -### ไปฃ็ ๆฃ€ๆŸฅ -```bash -npm run lint -``` +## ๐Ÿ™ Acknowledgments -## โš ๏ธ ๅฎ‰ๅ…จๆณจๆ„ไบ‹้กน +- 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` ๆ–‡ไปถๆไบคๅˆฐ็‰ˆๆœฌๆŽงๅˆถ -2. **ๅ‘ฝไปค็กฎ่ฎค**๏ผšAI ๅœจๆ‰ง่กŒไฟฎๆ”นๆ–‡ไปถๆˆ–่ฟ่กŒ็ณป็ปŸๅ‘ฝไปคๅ‰ไผš่ฏทๆฑ‚็กฎ่ฎค -3. **ๆƒ้™็ฎก็†**๏ผš็กฎไฟ AI ๅŠฉๆ‰‹ๅชๆœ‰ๅฟ…่ฆ็š„ๆ–‡ไปถ่ฎฟ้—ฎๆƒ้™ +## ๐Ÿ“ž Support -## ๐Ÿ“ ่ฎธๅฏ่ฏ - -MIT License - -## ๐Ÿค ่ดก็Œฎ - -ๆฌข่ฟŽๆไบค 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) - ไบคไบ’ๅผๅ‘ฝไปค่กŒ็•Œ้ข +- ๐Ÿ“ง Email: support@example.com +- ๐Ÿ’ฌ Discord: [Join our community](https://discord.gg/example) +- ๐Ÿ› Issues: [GitHub Issues](https://github.com/username/repo/issues) --- -**ๆ็คบ**๏ผšAI ๅŠฉๆ‰‹ไผšๅฐฝๅŠ›ๅธฎๅŠฉๆ‚จ๏ผŒไฝ†่ฏทๅง‹็ปˆๅฎกๆŸฅๅฎƒๅปบ่ฎฎ็š„ไปฃ็ ๆ›ดๆ”นๅ’Œๅ‘ฝไปคๆ‰ง่กŒ๏ผŒ็‰นๅˆซๆ˜ฏๅœจ็”Ÿไบง็Žฏๅขƒไธญใ€‚ \ No newline at end of file +
+ Made with โค๏ธ by the AI Terminal Assistant Team +
\ No newline at end of file diff --git a/packages/cli/README.md b/packages/cli/README.md new file mode 100644 index 0000000..6dfffa6 --- /dev/null +++ b/packages/cli/README.md @@ -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 to config file + --verbose Enable verbose logging +``` + +### Server Command + +```bash +ai-assist serve [options] + +Options: + -p, --port Server port (default: 3000) + -h, --host Server host (default: localhost) + --api-key Anthropic API key (or use ANTHROPIC_API_KEY env) + --model AI model to use + --max-tokens Maximum response tokens + --no-auth Disable authentication + --cors-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 Session ID to attach to + -t, --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 Attach a file to the next message +/model Switch AI model +/session new Start a new session +/session list List available sessions +/session switch Switch to another session +/export 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 < 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) \ No newline at end of file diff --git a/packages/core/README.md b/packages/core/README.md new file mode 100644 index 0000000..3604465 --- /dev/null +++ b/packages/core/README.md @@ -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; + streamChat(message: string, options?: StreamOptions): AsyncIterator; + 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; +} +``` + +### Editor Interface + +```typescript +interface Editor { + edit(path: string, content: string | EditParams): Promise; + 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) \ No newline at end of file diff --git a/packages/desktop/README.md b/packages/desktop/README.md new file mode 100644 index 0000000..20667db --- /dev/null +++ b/packages/desktop/README.md @@ -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 +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 { + // 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) \ No newline at end of file diff --git a/packages/server/README.md b/packages/server/README.md new file mode 100644 index 0000000..ad7b5a6 --- /dev/null +++ b/packages/server/README.md @@ -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 + +// Or in WebSocket +ws://server/api/ws/:sessionId?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) \ No newline at end of file diff --git a/packages/web/README.md b/packages/web/README.md new file mode 100644 index 0000000..a66635c --- /dev/null +++ b/packages/web/README.md @@ -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 ( + 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 ( +
+ {messages.map(msg => ( +
{msg.content}
+ ))} + +
+ ); +} +``` + +## โš™๏ธ 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(); + 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 ( + + ); +} +``` + +## ๐Ÿ“Š 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) \ No newline at end of file