feat: 重构为 Monorepo 架构并实现 HTTP Server

架构变更:
- 采用 pnpm workspaces 实现 Monorepo 结构
- 将现有代码迁移到 packages/core
- 新增 packages/server HTTP 服务层

Server 功能:
- REST API: 会话管理、工具管理、配置管理
- WebSocket: 实时双向通信支持
- SSE: 服务端事件推送
- Hono + Bun 作为运行时

API 端点:
- GET/POST /api/sessions - 会话 CRUD
- GET/POST /api/sessions/:id/messages - 消息管理
- GET /api/sessions/:id/events - SSE 事件流
- WS /api/ws/:sessionId - WebSocket 连接
- GET/POST /api/tools - 工具管理
- GET/PUT /api/config - 配置管理
This commit is contained in:
2025-12-12 10:42:20 +08:00
parent 59dbed926e
commit 5e32375f0e
301 changed files with 3281 additions and 43 deletions
+173
View File
@@ -0,0 +1,173 @@
/**
* AI Assistant Server
*
* HTTP Server 入口,提供 REST API、WebSocket 和 SSE 支持
*/
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { createBunWebSocket } from 'hono/bun';
import { sessionsRouter, toolsRouter, configRouter } from './routes/index.js';
import {
handleWebSocket,
handleWebSocketMessage,
handleWebSocketClose,
getConnectionStats,
} from './ws.js';
import { handleSSE, getSSEStats } from './sse.js';
import { getSessionManager } from './session/manager.js';
// 创建 Hono 应用
const app = new Hono();
// WebSocket 升级 (Bun 环境)
const { upgradeWebSocket, websocket } = createBunWebSocket();
// 中间件
app.use('*', logger());
app.use(
'*',
cors({
origin: '*', // 生产环境应该限制
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
})
);
// 健康检查
app.get('/health', (c) => {
const sessionManager = getSessionManager();
const wsStats = getConnectionStats();
const sseStats = getSSEStats();
return c.json({
status: 'ok',
timestamp: new Date().toISOString(),
stats: {
sessions: sessionManager.count(),
websocket: wsStats,
sse: sseStats,
},
});
});
// API 版本前缀
const api = new Hono();
// 挂载路由
api.route('/sessions', sessionsRouter);
api.route('/tools', toolsRouter);
api.route('/config', configRouter);
// SSE 事件流
api.get('/sessions/:id/events', handleSSE);
// WebSocket 端点
api.get(
'/ws/:sessionId',
upgradeWebSocket((c) => {
const sessionId = c.req.param('sessionId');
return {
onOpen(_event, ws) {
handleWebSocket(ws, sessionId);
},
onMessage(event, ws) {
handleWebSocketMessage(ws, sessionId, event.data);
},
onClose(_event, ws) {
handleWebSocketClose(ws, sessionId);
},
onError(event, ws) {
console.error('[WS] Error:', event);
handleWebSocketClose(ws, sessionId);
},
};
})
);
// 挂载 API 到 /api
app.route('/api', api);
// 404 处理
app.notFound((c) => {
return c.json(
{
success: false,
error: 'Not found',
},
404
);
});
// 错误处理
app.onError((err, c) => {
console.error('[Server Error]', err);
return c.json(
{
success: false,
error: err.message || 'Internal server error',
},
500
);
});
// 服务器配置
export interface ServerOptions {
port?: number;
host?: string;
}
/**
* 创建服务器实例
*/
export function createServer(options: ServerOptions = {}) {
const { port = 3000, host = '127.0.0.1' } = options;
return {
app,
websocket,
port,
host,
};
}
/**
* 启动服务器 (Bun 环境)
*/
export function startServer(options: ServerOptions = {}): void {
const { port = 3000, host = '127.0.0.1' } = options;
console.log(`
╔════════════════════════════════════════════╗
║ AI Assistant Server ║
╠════════════════════════════════════════════╣
║ REST API: http://${host}:${port}/api
║ WebSocket: ws://${host}:${port}/api/ws/:sessionId
║ SSE: http://${host}:${port}/api/sessions/:id/events
║ Health: http://${host}:${port}/health
╚════════════════════════════════════════════╝
`);
// Bun.serve 需要在 CLI 包中调用
// 这里只导出配置
}
// 导出
export { app, websocket };
export { getSessionManager } from './session/manager.js';
export { registerTool, getRegisteredTools } from './routes/tools.js';
export { getConfig, setConfig } from './routes/config.js';
export {
emitEvent,
broadcastEvent,
emitStatusEvent,
emitLogEvent,
emitProgressEvent,
emitFileChangeEvent,
} from './sse.js';
export { broadcastToSession } from './ws.js';
export * from './types.js';