35 lines
1.7 KiB
TypeScript
35 lines
1.7 KiB
TypeScript
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
import { CLOUD_AGENTS_PATH } from '../../../shared/cloud-agents';
|
|
import { CloudAgentsError, CloudAgentsModule } from '../../services/cloud-agents';
|
|
import { parseJsonBody, sendJson } from '../route-utils';
|
|
|
|
const cloudAgents = new CloudAgentsModule();
|
|
|
|
export async function handleCloudAgentsRoutes(req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
|
|
if (!url.pathname.startsWith(CLOUD_AGENTS_PATH + '/')) return false;
|
|
res.setHeader('Cache-Control', 'no-store');
|
|
const path = url.pathname.slice(CLOUD_AGENTS_PATH.length);
|
|
try {
|
|
let data: unknown;
|
|
if ((path === '/bootstrap' || path === '/agents') && req.method === 'GET') {
|
|
data = await cloudAgents.list(url.searchParams.get('cursor'));
|
|
} else if (path === '/agents' && req.method === 'POST') {
|
|
data = await cloudAgents.create(await parseJsonBody(req));
|
|
} else {
|
|
const match = /^\/agents\/(ml-[a-f0-9]{32})(\/draft)?$/.exec(path);
|
|
if (match && !match[2] && req.method === 'GET') data = await cloudAgents.get(match[1]);
|
|
else if (match && match[2] && req.method === 'PATCH') data = await cloudAgents.save(match[1], await parseJsonBody(req));
|
|
else {
|
|
sendJson(res, 404, { error: '智能体接口不存在' });
|
|
return true;
|
|
}
|
|
}
|
|
sendJson(res, 200, data);
|
|
} catch (error) {
|
|
const failure = error instanceof CloudAgentsError ? error
|
|
: new CloudAgentsError(error instanceof SyntaxError ? 400 : 502, error instanceof SyntaxError ? 'invalid_input' : 'cloud_service_unavailable');
|
|
sendJson(res, failure.status, { success: false, error: failure.message, code: failure.code });
|
|
}
|
|
return true;
|
|
}
|