Team Ai
Apppublic

delqhi/code-devops

sourceHugging Faceupdated 6mo agoView on Hugging Face
0likes
a2a-http.ts79 linesDownload Raw Back to src
1import { randomUUID } from 'node:crypto';2import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';3import { buildAgentCard, resolveTemplateAgentConfig, TEMPLATE_AGENT_ID, TEMPLATE_AGENT_NAME } from './metadata.js';4import { executeTemplateAgentAction, type TemplateAgentAction } from './runtime.js';5 6type RpcRequest = { jsonrpc?: string; id?: string | number | null; method?: string; params?: Record<string, unknown> };7 8export function createTemplateAgentHttpServer() {9  const config = resolveTemplateAgentConfig();10  const server = createServer((request, response) => void handleRequest(request, response, config.publicBaseUrl));11  return {12    server,13    async start() {14      await new Promise<void>((resolve, reject) => {15        server.once('error', reject);16        server.listen(config.port, config.host, () => resolve());17      });18    },19    async stop() {20      await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));21    },22  };23}24 25async function handleRequest(request: IncomingMessage, response: ServerResponse, baseUrl: string) {26  if (request.method === 'GET' && request.url === '/health') return sendJson(response, 200, { ok: true, agent: TEMPLATE_AGENT_ID });27  if (request.method === 'GET' && request.url === '/') return sendHtml(response, 200, `<html><body><h1>${TEMPLATE_AGENT_NAME}</h1></body></html>`);28  if (request.method === 'GET' && (request.url === '/.well-known/agent-card.json' || request.url === '/.well-known/agent.json')) {29    return sendJson(response, 200, buildAgentCard(baseUrl));30  }31  if (request.method === 'POST' && request.url === '/a2a/v1') {32    const rpc = ((await readJson(request)) || {}) as RpcRequest;33    if (rpc.method === 'agent/getCard') return sendJson(response, 200, { jsonrpc: '2.0', id: rpc.id ?? null, result: buildAgentCard(baseUrl) });34    if (rpc.method === 'message/send') {35      const action = parseAction((rpc.params?.message as { parts?: Array<{ text?: string }> } | undefined)?.parts?.map((part) => part.text || '').join(' ').trim() || '');36      const result = await executeTemplateAgentAction(action);37      return sendJson(response, 200, {38        jsonrpc: '2.0',39        id: rpc.id ?? null,40        result: {41          id: randomUUID(),42          kind: 'task',43          status: { state: 'completed', timestamp: new Date().toISOString(), message: { role: 'agent', parts: [{ type: 'text', text: 'done' }] } },44          artifacts: [{ id: randomUUID(), name: action.action, description: action.action, parts: [{ type: 'data', data: result }] }],45          metadata: { action: action.action },46        },47      });48    }49  }50  sendJson(response, 404, { error: 'not_found' });51}52 53function parseAction(text: string): TemplateAgentAction {54  const value = text.toLowerCase();55  if (value === 'sin.code.devops health') return { action: 'sin.code.devops.health' };56  if (value === 'sin.code.devops onboarding status') return { action: 'sin.code.devops.onboarding.status' };57  return { action: 'agent.help' };58}59 60async function readJson(request: IncomingMessage) {61  const chunks: Buffer[] = [];62  for await (const chunk of request) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));63  const raw = Buffer.concat(chunks).toString('utf8').trim();64  return raw ? JSON.parse(raw) : null;65}66 67function sendJson(response: ServerResponse, statusCode: number, payload: unknown) {68  response.statusCode = statusCode;69  response.setHeader('content-type', 'application/json; charset=utf-8');70  response.end(JSON.stringify(payload, null, 2));71}72 73function sendHtml(response: ServerResponse, statusCode: number, payload: string) {74  response.statusCode = statusCode;75  response.setHeader('content-type', 'text/html; charset=utf-8');76  response.end(payload);77}78 79