dsh-brain/lib/skills/routes.js

463 lines
20 KiB
JavaScript

import { randomUUID } from 'node:crypto';
import { SkillAdminError } from "../skill-admin.js";
import { SkillGroupError } from "../skill-groups.js";
import { MarketError } from "../market.js";
import { renderSkillsPage } from "../skill-page.js";
import { fail, json, jsonBody } from "../http.js";
/** Path constants — kept in sync with the ROUTES map in routes.ts by hand. */
const PATHS = {
skills: '/dsh-brain/skills',
market: '/dsh-brain/market',
clients: '/dsh-brain/clients',
};
/**
* Uninstall confirmations.
*
* A preview issues a single-use token bound to one folder; the delete route
* refuses without it, so a stray click cannot remove a skill.
*/
const uninstallTokens = new Map();
const UNINSTALL_TOKEN_TTL_MS = 10 * 60_000;
/** HTTP status for one skill-admin failure code. */
function adminStatus(code) {
switch (code) {
case 'not_found': return 404;
case 'invalid_name':
case 'invalid_url':
case 'invalid_plan': return 400;
case 'collision':
case 'sync_running':
case 'plan_expired':
case 'confirmation_required':
case 'no_source':
case 'up_to_date':
case 'stale_plan':
case 'unsupported': return 409;
case 'no_backup': return 404;
case 'no_skills_found': return 422;
case 'git_failed': return 502;
default: return 500;
}
}
/** Issue the single-use token a delete needs. */
function issueUninstallToken(folder) {
const token = `uninstall_${randomUUID()}`;
uninstallTokens.set(folder, { token, expiresAt: Date.now() + UNINSTALL_TOKEN_TTL_MS });
return token;
}
/** Consume one uninstall token; false when it is missing, stale or foreign. */
function useUninstallToken(folder, token) {
const record = uninstallTokens.get(folder);
if (record === undefined)
return false;
if (typeof token !== 'string' || token !== record.token)
return false;
if (record.expiresAt < Date.now()) {
uninstallTokens.delete(folder);
return false;
}
uninstallTokens.delete(folder);
return true;
}
/**
* The skill management surface, one prefix route:
* `GET /dsh-brain/skills` the management page
* `GET /dsh-brain/skills/api` inventory JSON (skills + plans)
* `POST /dsh-brain/skills/detail` { folder } — one skill with SKILL.md
* `POST /dsh-brain/skills/toggle` { folder, enabled }
* `POST /dsh-brain/skills/install/plan` { url } — stage the repository
* `POST /dsh-brain/skills/install/commit` { planId, folders }
* `POST /dsh-brain/skills/install/cancel` { planId }
* `POST /dsh-brain/skills/uninstall/plan` { folder } — impact preview
* `POST /dsh-brain/skills/remove` { folder, token, confirmed: true }
*/
async function serveSkills(deps, req, res) {
const admin = deps.admin;
if (admin === undefined) {
fail(res, 404, 'skills-admin-unavailable');
return;
}
const suffix = (req.url ?? '').split('?')[0]?.slice(PATHS.skills.length) ?? '';
if (suffix === '' || suffix === '/') {
if (req.method !== 'GET' && req.method !== 'HEAD') {
fail(res, 405, 'method-not-allowed', true);
return;
}
const html = renderSkillsPage({ version: deps.version });
res.writeHead(200, {
'content-type': 'text/html; charset=utf-8',
'cache-control': 'no-store',
'content-length': Buffer.byteLength(html),
});
if (req.method === 'HEAD')
res.end();
else
res.end(html);
return;
}
if (suffix === '/api') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
const inventory = await admin.list();
json(res, 200, { ok: true, ...inventory, ...(await admin.listPlans()) });
return;
}
if (suffix === '/sources') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
const groups = deps.groups;
if (groups === undefined) {
fail(res, 404, 'skill-groups-unavailable');
return;
}
json(res, 200, { ok: true, ...(await groups.overview()) });
return;
}
const actions = {
'/detail': async (body) => ({ ...(await admin.detail(body.folder)) }),
'/toggle': async (body) => ({ ...(await admin.setEnabled(body.folder, body.enabled === true)) }),
// One-shot install kept for the standalone page; the card uses plan/commit.
'/install': async (body) => ({ ...(await admin.installFromGit(body.url)) }),
'/install/plan': async (body) => ({ ...(await admin.prepareInstall(body.url)) }),
'/install/commit': async (body) => ({ ...(await admin.commitInstall({ planId: body.planId, folders: body.folders })) }),
'/install/cancel': async (body) => ({ ...(await admin.cancelInstall({ planId: body.planId })) }),
'/uninstall/plan': async (body) => {
const plan = await admin.uninstallPlan(body.folder);
return { ...plan, token: issueUninstallToken(plan.folder) };
},
'/remove': async (body) => {
if (body.confirmed !== true) {
throw new SkillAdminError('confirmation_required', '删除必须显式确认:先预览影响,再传 confirmed=true。');
}
const folder = typeof body.folder === 'string' ? body.folder : '';
if (!useUninstallToken(folder, body.token)) {
throw new SkillAdminError('confirmation_required', '卸载确认已过期或与该技能不匹配,请重新预览。');
}
return { ...(await admin.remove(folder)) };
},
};
// Update/rollback operate on skills with a `.skill-source.json` record. They
// are optional: without the updater wired in the routes answer 404.
const updateActions = {
'/update/check': async (body) => ({ ...(await requireUpdates(deps).checkUpdate(body.folder)) }),
'/update/apply': async (body) => ({ ...(await requireUpdates(deps).applyUpdate(body.folder, body.expectedCommit)) }),
'/rollback': async (body) => ({ ...(await requireUpdates(deps).rollback(body.folder)) }),
};
// Category and source switches live in the same prefix so the card has one
// base URL; they are grouped here because they never touch a skill folder
// directly (except the DSH park/unpark the group manager delegates).
const groupActions = {
'/import': async (body) => ({ ...(await requireGroups(deps).importSkill(body.sourceId, body.folder)) }),
'/groups/create': async (body) => ({ ...(await requireGroups(deps).createGroup(body.sourceId, body.name)) }),
'/groups/rename': async (body) => ({ ...(await requireGroups(deps).renameGroup(body.sourceId, body.groupId, body.name)) }),
'/groups/delete': async (body) => ({ ...(await requireGroups(deps).deleteGroup(body.sourceId, body.groupId)) }),
'/groups/assign': async (body) => ({ ...(await requireGroups(deps).assign(body.sourceId, body.groupId, body.folders)) }),
'/groups/toggle': async (body) => ({ ...(await requireGroups(deps).toggleGroup(body.sourceId, body.groupId, body.enabled === true)) }),
'/source/toggle': async (body) => ({ ...(await requireGroups(deps).toggleSource(body.sourceId, body.enabled === true)) }),
'/source/reveal': async (body) => ({ ...(await requireGroups(deps).reveal(body.sourceId)) }),
};
const action = actions[suffix] ?? groupActions[suffix] ?? updateActions[suffix];
if (action === undefined) {
fail(res, 404, 'unknown-skill-route');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
try {
json(res, 200, { ok: true, ...(await action(body)) });
}
catch (error) {
if (error instanceof SkillAdminError) {
json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message });
return;
}
if (error instanceof SkillGroupError) {
json(res, groupStatus(error.code), { ok: false, code: error.code, error: error.message });
return;
}
json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) });
}
}
/** The group manager is optional; the routes answer 404 when it is absent. */
function requireGroups(deps) {
if (deps.groups === undefined)
throw new SkillGroupError('unavailable', '技能分组功能未启用。');
return deps.groups;
}
/** HTTP status for one group failure code. */
function groupStatus(code) {
switch (code) {
case 'not_found':
case 'unknown_source': return 404;
case 'invalid_name':
case 'duplicate':
case 'import_from_self':
case 'invalid_skill':
case 'too_many': return 400;
case 'unavailable': return 503;
default: return 500;
}
}
/** The updater is optional; its routes answer 404 when it is absent. */
function requireUpdates(deps) {
if (deps.updates === undefined)
throw new SkillAdminError('unsupported', '技能更新/回退未启用。');
return deps.updates;
}
/** HTTP status for one market failure code. */
function marketStatus(code) {
switch (code) {
case 'unknown_provider':
case 'invalid_manifest': return 400;
case 'not_found': return 404;
case 'unreachable':
case 'unavailable': return 502;
default:
return code.startsWith('http_') ? 502 : 500;
}
}
/**
* Market surface, one prefix route:
* `GET /dsh-brain/market/providers` configured sources
* `GET /dsh-brain/market/search` ?provider=&q=&cursor=
* `POST /dsh-brain/market/detail` { provider, id }
* `POST /dsh-brain/market/plan` { provider, id } — pin commit + stage a plan
* `POST /dsh-brain/market/commit` { planId, folders }
* `POST /dsh-brain/market/cancel` { planId }
*/
async function serveMarket(deps, req, res) {
const market = deps.market;
if (market === undefined) {
fail(res, 404, 'market-unavailable');
return;
}
const url = new URL(req.url ?? '/', 'http://localhost');
const suffix = url.pathname.slice(PATHS.market.length);
try {
if (suffix === '' || suffix === '/' || suffix === '/providers') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
json(res, 200, { ok: true, providers: market.list() });
return;
}
if (suffix === '/search') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
const providerId = url.searchParams.get('provider') ?? market.list()[0]?.id ?? '';
const query = url.searchParams.get('q') ?? '';
const cursorRaw = Number(url.searchParams.get('cursor') ?? '0');
const cursor = Number.isFinite(cursorRaw) && cursorRaw > 0 ? cursorRaw : 0;
const result = await market.search(providerId, query, cursor);
json(res, 200, { ok: true, provider: market.get(providerId).info(), ...result });
return;
}
const admin = deps.admin;
const requireAdmin = () => {
if (admin === undefined)
throw new MarketError('unavailable', '技能管理未启用,无法安装。');
return admin;
};
const actions = {
'/detail': async (body) => ({ ...(await market.detail(String(body.provider ?? ''), String(body.id ?? ''))) }),
'/plan': async (body) => {
const providerId = String(body.provider ?? '');
const id = String(body.id ?? '');
const artifact = await market.resolve(providerId, id, typeof body.version === 'string' ? body.version : undefined);
const plan = await requireAdmin().prepareInstall(artifact.repoUrl, {
ref: artifact.ref,
source: {
provider: providerId,
entryId: id,
...(artifact.version === undefined ? {} : { version: artifact.version }),
},
});
const wanted = new Set(artifact.folders);
return {
planId: plan.planId,
...(plan.commit === undefined ? {} : { commit: plan.commit }),
artifact,
candidates: plan.candidates.filter((candidate) => wanted.has(candidate.folder)),
totalInRepo: plan.candidates.length,
};
},
'/commit': async (body) => ({ ...(await requireAdmin().commitInstall({ planId: body.planId, folders: body.folders })) }),
'/cancel': async (body) => ({ ...(await requireAdmin().cancelInstall({ planId: body.planId })) }),
};
const action = actions[suffix];
if (action === undefined) {
fail(res, 404, 'unknown-market-route');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
json(res, 200, { ok: true, ...(await action(body)) });
}
catch (error) {
if (error instanceof MarketError) {
json(res, marketStatus(error.code), { ok: false, code: error.code, error: error.message });
return;
}
if (error instanceof SkillAdminError) {
json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message });
return;
}
json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) });
}
}
/** Cross-software / workspace inventory routes. */
async function serveClients(deps, req, res) {
const registry = deps.clients;
if (registry === undefined) {
fail(res, 404, 'clients-unavailable');
return;
}
const url = new URL(req.url ?? '/', 'http://localhost');
const suffix = url.pathname.slice(PATHS.clients.length);
try {
if (suffix === '' || suffix === '/' || suffix === '/overview') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
json(res, 200, { ok: true, ...(await registry.overview()) });
return;
}
if (suffix === '/inventory') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
const result = await registry.inventory(url.searchParams.get('software'), url.searchParams.get('scope'), url.searchParams.get('workspaceId') ?? undefined);
json(res, 200, { ok: true, ...result });
return;
}
if (suffix === '/workspaces/add') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const workspace = await registry.addWorkspace(body.software, body.path, body.name);
json(res, 200, { ok: true, workspace });
return;
}
if (suffix === '/workspaces/remove') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
json(res, 200, { ok: true, ...(await registry.removeWorkspace(body.software, body.id)) });
return;
}
if (suffix === '/workspace/inventory') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
const { admin, workspace } = await registry.workspaceSkillAdmin(url.searchParams.get('software'), url.searchParams.get('workspaceId'));
json(res, 200, { ok: true, workspace, ...(await admin.list()) });
return;
}
if (suffix === '/workspace/detail') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
json(res, 200, { ok: true, ...(await admin.detail(body.folder)) });
return;
}
if (suffix === '/workspace/toggle') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
json(res, 200, { ok: true, ...(await admin.setEnabled(body.folder, body.enabled === true)) });
return;
}
if (suffix === '/workspace/remove') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
if (body.confirmed !== true)
throw new SkillAdminError('confirmation_required', '工作区技能删除必须显式 confirmed:true。');
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
json(res, 200, { ok: true, ...(await admin.remove(body.folder)) });
return;
}
if (suffix === '/workspace/install/plan') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
json(res, 200, { ok: true, ...(await admin.prepareInstall(body.url)) });
return;
}
if (suffix === '/workspace/install/commit') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
json(res, 200, { ok: true, ...(await admin.commitInstall({ planId: body.planId, folders: body.folders })) });
return;
}
fail(res, 404, 'unknown-clients-route');
}
catch (error) {
if (error instanceof SkillAdminError) {
json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message });
return;
}
const message = error instanceof Error ? error.message : String(error);
const known = ['invalid_software', 'invalid_path', 'duplicate', 'not_found', 'unknown_workspace', 'unsupported_workspace_write'];
const code = known.includes(message) ? message : 'internal';
const status = code === 'internal' ? 500
: code === 'not_found' || code === 'unknown_workspace' ? 404
: code === 'duplicate' ? 409
: code === 'unsupported_workspace_write' ? 501 : 400;
json(res, status, { ok: false, code, error: message });
}
}
/** Skill-bundle routes; the root aggregator decides the registration order. */
export function createSkillRoutes(deps) {
return [
{ kind: 'prefix', path: PATHS.skills, handler: (req, res) => serveSkills(deps, req, res) },
{ kind: 'prefix', path: PATHS.market, handler: (req, res) => serveMarket(deps, req, res) },
{ kind: 'prefix', path: PATHS.clients, handler: (req, res) => serveClients(deps, req, res) },
];
}