import type { IncomingMessage, ServerResponse } from 'node:http'; import { isAgentSystemDocumentKind, readAgentSystemDocuments, resetAgentSystemDocument, saveAgentSystemDocument, } from '../../utils/agent-system-documents'; import type { HostApiContext } from '../context'; import { parseJsonBody, sendJson } from '../route-utils'; function scheduleGatewayReload(ctx: HostApiContext): void { if (ctx.gatewayManager.getStatus().state !== 'stopped') { ctx.gatewayManager.debouncedReload(); } } function parseDocumentPath(url: URL): { kind: string; reset: boolean } | null { const prefix = '/api/agent-system-documents/'; if (!url.pathname.startsWith(prefix)) return null; const parts = url.pathname.slice(prefix.length).split('/').filter(Boolean); if (parts.length === 1) { return { kind: decodeURIComponent(parts[0]), reset: false }; } if (parts.length === 2 && parts[1] === 'reset') { return { kind: decodeURIComponent(parts[0]), reset: true }; } return null; } export async function handleAgentSystemDocumentRoutes( req: IncomingMessage, res: ServerResponse, url: URL, ctx: HostApiContext, ): Promise { if (url.pathname === '/api/agent-system-documents' && req.method === 'GET') { try { sendJson(res, 200, await readAgentSystemDocuments(url.searchParams.get('agentId') ?? undefined)); } catch (error) { sendJson(res, 500, { success: false, error: String(error) }); } return true; } const parsed = parseDocumentPath(url); if (!parsed) return false; if (!isAgentSystemDocumentKind(parsed.kind)) { sendJson(res, 404, { success: false, error: `Unsupported system document kind "${parsed.kind}"` }); return true; } if (!parsed.reset && req.method === 'PUT') { try { const body = await parseJsonBody<{ agentId?: string; content?: string }>(req); const snapshot = await saveAgentSystemDocument(body.agentId, parsed.kind, body.content ?? ''); scheduleGatewayReload(ctx); sendJson(res, 200, snapshot); } catch (error) { sendJson(res, 500, { success: false, error: String(error) }); } return true; } if (parsed.reset && req.method === 'POST') { try { const body = await parseJsonBody<{ agentId?: string }>(req); const snapshot = await resetAgentSystemDocument(body.agentId, parsed.kind); scheduleGatewayReload(ctx); sendJson(res, 200, snapshot); } catch (error) { sendJson(res, 500, { success: false, error: String(error) }); } return true; } return false; }