Files
ai-terminal-assistant/packages/server
kurihada 67e129fce2 fix(commands): 修复路由顺序导致 /content 端点被遮蔽的问题
- 将 /:name{.+}/execute 和 /:name{.+}/content 路由移到 /:name{.+} 之前
- Hono 的 {.+} 模式会贪婪匹配,导致 /test/content 被解析为 name='test/content'
- 更新测试用例以正确测试 /content 端点功能
2025-12-15 00:17:22 +08:00
..
2025-12-12 14:28:34 +08:00
2025-12-12 15:31:38 +08:00

@ai-assistant/server

HTTP/WebSocket server for AI Terminal Assistant - provides REST API, WebSocket, and SSE endpoints.

📦 Installation

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

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

# 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

// 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

// List available tools
GET /api/tools
Response: Tool[]

// Execute tool
POST /api/tools/:name/execute
Body: { params: any, sessionId?: string }
Response: { result: any }

Configuration

// 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

// 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

// 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

# 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

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:

// 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

# Run tests
pnpm test

# Run with coverage
pnpm test:coverage

# E2E tests
pnpm test:e2e

Test Examples

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

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

// 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

curl http://localhost:3000/api/health
# Response: { status: 'healthy', uptime: 123456, sessions: 5 }

Metrics Endpoint

curl http://localhost:3000/api/metrics
# Response: Prometheus-formatted metrics

🚀 Deployment

Docker

FROM oven/bun:1.0
WORKDIR /app
COPY package*.json ./
RUN bun install
COPY . .
EXPOSE 3000
CMD ["bun", "run", "start"]

PM2

{
  "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 for details.