sin-github-issues / src /a2a-http.ts
OpenCode
Deploy latest SIN-GitHub-Issues runtime
cd455f6
Raw
History Blame Contribute Delete
6.08 kB
import { randomUUID } from 'node:crypto';
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import type { GitHubAgentAction } from './runtime.js';
import { listGitHubAppWebhookPaths, routeGitHubWebhook } from './github-app-routing.js';
import { buildAgentCard, resolveTemplateAgentConfig, TEMPLATE_AGENT_ID, TEMPLATE_AGENT_NAME } from './metadata.js';
import { executeGitHubAgentAction } from './runtime.js';
type RpcRequest = { jsonrpc?: string; id?: string | number | null; method?: string; params?: Record<string, unknown> };
export function createTemplateAgentHttpServer() {
const config = resolveTemplateAgentConfig();
const server = createServer((request, response) => void handleRequest(request, response, config.publicBaseUrl));
return {
server,
async start() {
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(config.port, config.host, () => resolve());
});
},
async stop() {
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
},
};
}
async function handleRequest(request: IncomingMessage, response: ServerResponse, baseUrl: string) {
const routePath = normalizePath(request.url || '/');
if (request.method === 'GET' && request.url === '/health') return sendJson(response, 200, { ok: true, agent: TEMPLATE_AGENT_ID });
if (request.method === 'GET' && request.url === '/') return sendHtml(response, 200, `<html><body><h1>${TEMPLATE_AGENT_NAME}</h1></body></html>`);
if (request.method === 'GET' && (request.url === '/.well-known/agent-card.json' || request.url === '/.well-known/agent.json')) {
return sendJson(response, 200, buildAgentCard(baseUrl));
}
const configuredWebhookPaths = request.method === 'POST' ? await listGitHubAppWebhookPaths() : [];
if (request.method === 'POST' && configuredWebhookPaths.some((configuredPath) => routePath === configuredPath || routePath.startsWith(`${configuredPath}/`))) {
const rawBody = await readRawBody(request);
const payload = rawBody.trim() ? JSON.parse(rawBody) : {};
const result = await routeGitHubWebhook({
payload,
rawBody,
routePath,
signature256: readHeader(request, 'x-hub-signature-256'),
eventName: readHeader(request, 'x-github-event'),
deliveryId: readHeader(request, 'x-github-delivery'),
});
return sendJson(response, result.ok ? 200 : 400, result);
}
if (request.method === 'POST' && request.url === '/a2a/v1') {
const rpc = ((await readJson(request)) || {}) as RpcRequest;
if (rpc.method === 'agent/getCard') return sendJson(response, 200, { jsonrpc: '2.0', id: rpc.id ?? null, result: buildAgentCard(baseUrl) });
if (rpc.method === 'message/send') {
const action = parseAction((rpc.params?.message as { parts?: Array<{ text?: string }> } | undefined)?.parts?.map((part) => part.text || '').join(' ').trim() || '');
const result = await executeGitHubAgentAction(action);
return sendJson(response, 200, {
jsonrpc: '2.0',
id: rpc.id ?? null,
result: {
id: randomUUID(),
kind: 'task',
status: { state: 'completed', timestamp: new Date().toISOString(), message: { role: 'agent', parts: [{ type: 'text', text: 'done' }] } },
artifacts: [{ id: randomUUID(), name: action.action, description: action.action, parts: [{ type: 'data', data: result }] }],
metadata: { action: action.action },
},
});
}
}
sendJson(response, 404, { error: 'not_found' });
}
function parseAction(text: string): GitHubAgentAction {
try {
const parsed = JSON.parse(text);
if (parsed && typeof parsed === 'object' && typeof parsed.action === 'string') return parsed as GitHubAgentAction;
} catch { /* not JSON, fall through to text matching */ }
const value = text.toLowerCase().trim();
if (value.includes('health')) return { action: 'sin.github.health' };
if (value.includes('project')) return { action: 'sin.github.project.orchestrate', prompt: text };
if (value.includes('wiki')) return { action: 'sin.github.wiki.sync', prompt: text };
if (value.includes('discussion')) return { action: 'sin.github.discussion.start', prompt: text };
if (value.includes('gist')) return { action: 'sin.github.gist.publish', prompt: text };
if (value.includes('security') || value.includes('audit')) return { action: 'sin.github.security.audit', prompt: text };
if (value.includes('pr') || value.includes('pull request') || value.includes('review')) return { action: 'sin.github.pr.review', prNumber: 0 };
if (value.includes('ledger') || value.includes('showcase')) return { action: 'sin.github.ledger.log', agentName: 'unknown', activityTitle: text, details: text };
if (value.includes('issue')) return { action: 'sin.github.issue.manage', prompt: text };
return { action: 'agent.help' };
}
async function readJson(request: IncomingMessage) {
const raw = (await readRawBody(request)).trim();
return raw ? JSON.parse(raw) : null;
}
async function readRawBody(request: IncomingMessage) {
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
return Buffer.concat(chunks).toString('utf8');
}
function readHeader(request: IncomingMessage, name: string) {
const value = request.headers[name];
return typeof value === 'string' ? value : Array.isArray(value) ? value.join(',') : undefined;
}
function normalizePath(url: string) {
return url.split('?', 1)[0] || '/';
}
function sendJson(response: ServerResponse, statusCode: number, payload: unknown) {
response.statusCode = statusCode;
response.setHeader('content-type', 'application/json; charset=utf-8');
response.end(JSON.stringify(payload, null, 2));
}
function sendHtml(response: ServerResponse, statusCode: number, payload: string) {
response.statusCode = statusCode;
response.setHeader('content-type', 'text/html; charset=utf-8');
response.end(payload);
}