| import { serve } from '@hono/node-server'; |
| import { Hono } from 'hono'; |
| import { rateLimit } from 'express-rate-limit'; |
| import { readFileSync } from 'node:fs'; |
| import { join } from 'node:path'; |
| import { executeBackendAgentAction, BackendAgentAction } from './runtime.js'; |
|
|
| export function runHttpServer() { |
| const app = new Hono(); |
| const PORT = Number(process.env.PORT) || 8080; |
|
|
| const rateLimiter = rateLimit({ |
| windowMs: 60 * 1000, |
| max: 100, |
| message: 'Too many requests, please try again later.', |
| }); |
|
|
| app.use('*', async (c, next) => { |
| return new Promise<void>((resolve) => { |
| const env = (c as any).env as any; |
| rateLimiter(env?.req as any, env?.res as any, () => { |
| next().then(resolve); |
| }); |
| }); |
| }); |
|
|
| app.get('/health', (c) => c.json({ status: 'ok', agent: 'sin-backend' })); |
|
|
| app.get('/.well-known/agent-card.json', (c) => { |
| try { |
| const card = readFileSync(join(process.cwd(), '.well-known', 'agent-card.json'), 'utf8'); |
| return c.json(JSON.parse(card)); |
| } catch { |
| return c.json({ error: 'Agent card not found' }, 404); |
| } |
| }); |
|
|
| app.get('/.well-known/agent.json', (c) => { |
| try { |
| const spec = readFileSync(join(process.cwd(), '.well-known', 'agent.json'), 'utf8'); |
| return c.json(JSON.parse(spec)); |
| } catch { |
| return c.json({ error: 'Agent spec not found' }, 404); |
| } |
| }); |
|
|
| app.post('/a2a/v1', async (c) => { |
| try { |
| const body = await c.req.json(); |
| |
| const rpcMethod = body.method; |
| let action: BackendAgentAction; |
|
|
| if (rpcMethod === 'sin.backend.health') { |
| action = { action: 'sin.backend.health' }; |
| } else if (rpcMethod === 'sin.backend.code.generate') { |
| action = { action: 'sin.backend.code.generate', prompt: body.params?.prompt, contextDir: body.params?.contextDir }; |
| } else if (rpcMethod === 'sin.backend.code.review') { |
| action = { action: 'sin.backend.code.review', targetDir: body.params?.targetDir }; |
| } else if (rpcMethod === 'agent.help' || body.action === 'agent.help') { |
| action = { action: 'agent.help' }; |
| } else { |
| return c.json({ error: { code: -32601, message: 'Method not found' } }, 400); |
| } |
|
|
| const result = await executeBackendAgentAction(action); |
| return c.json({ jsonrpc: '2.0', id: body.id || null, result }); |
| } catch (e: any) { |
| return c.json({ error: { code: -32000, message: e.message } }, 500); |
| } |
| }); |
|
|
| serve({ fetch: app.fetch, port: PORT }, (info) => { |
| console.log(`SIN-Backend HTTP A2A server running at http://localhost:${info.port}`); |
| }); |
| } |
|
|