# @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)