更新 lib/routes.js

This commit is contained in:
QQ 2026-11-12 00:01:34 +08:00
parent 95c9187e5b
commit 8dd2bad4f3
1 changed files with 657 additions and 76 deletions

View File

@ -1,19 +1,64 @@
import { describeError, isSecureLoginTarget } from "./api.js";
import { renderConfigPage } from "./page.js";
import { SkillAdminError } from "./skill-admin.js";
import { MarketError } from "./market.js";
import { brainStatus, migrateLegacyFiles } from "./brain-migration.js";
import { SkillGroupError } from "./skill-groups.js";
import { renderSkillsPage } from "./skill-page.js";
import { randomUUID } from 'node:crypto';
/** Route constants — kept in one place so the client half can reuse them. */
export const ROUTES = {
page: '/dsh-brain',
status: '/dsh-brain/status',
capabilities: '/dsh-brain/capabilities',
config: '/dsh-brain/config',
login: '/dsh-brain/login',
test: '/dsh-brain/test',
flush: '/dsh-brain/flush',
skills: '/dsh-brain/skills',
market: '/dsh-brain/market',
sync: '/dsh-brain/sync',
clients: '/dsh-brain/clients',
migrate: '/dsh-brain/migrate',
};
/** Largest request body we accept (a settings patch is tiny). */
const MAX_BODY_BYTES = 64 * 1024;
/** What this build actually implements, stated per feature. */
function capabilities(deps) {
const marketProviders = deps.market?.list().length ?? 0;
return {
version: deps.version,
features: {
connection: true,
identitySwitch: true,
skills: deps.admin !== undefined,
skillInstallPlans: deps.admin !== undefined,
skillUninstallPlan: deps.admin !== undefined,
skillsSync: deps.skills !== undefined,
skillsMarketplace: deps.market !== undefined,
marketProviders,
skillUpdate: deps.updates !== undefined,
syncResolve: deps.sync !== undefined,
multiClient: deps.clients !== undefined,
brainMigration: 'ready',
// The MCP bridge is provided by the host `dsh-mcp-connector` plugin over
// the same origin; the browser half probes it at runtime.
mcpBridge: 'host-plugin',
},
notes: [
...(deps.market === undefined
? ['技能市场未启用:没有配置市场来源。']
: [`技能市场已接入 ${marketProviders} 个来源;安装走暂存计划并固定提交。`]),
...(deps.updates === undefined
? ['技能更新/回退未启用。']
: ['更新/回退仅对带来源记录(.skill-source.json)的技能生效,更新前自动备份。']),
...(deps.sync === undefined ? [] : ['同步冲突可在技能页签逐项“保留本地 / 采用云端 / 手动合并”。']),
...(deps.clients === undefined ? [] : ['跨软件与工作区技能清单为只读(DSH 之外不写目录);dsh-brain 数据迁移已就绪,实际改名需部署重启。']),
'MCP 管理由宿主 dsh-mcp-connector 插件提供,本卡通过其公开接口读写,不另建凭据库。',
'MCP 工具可见性与会话级激活分属两层:本卡展示连接与工具缓存,会话级“选择精确工具后激活”由宿主 session-tools 负责,本卡不伪造激活。',
],
};
}
/** Collect a request body as UTF-8 text. */
async function readBody(req, maxBytes = MAX_BODY_BYTES) {
const chunks = [];
@ -56,6 +101,50 @@ function fail(res, status, message, asHtml = false) {
});
res.end(text);
}
/**
* Read one JSON object body, or answer the request and return undefined.
*
* The method, origin and content-type gates live here so every write route
* cannot forget one of them.
*/
async function jsonBody(req, res) {
if (req.method !== 'POST' && req.method !== 'PUT') {
fail(res, 405, 'method-not-allowed');
return undefined;
}
if (!sameOrigin(req)) {
fail(res, 403, 'origin-rejected');
return undefined;
}
const type = (req.headers['content-type'] ?? '').toLowerCase();
if (!type.startsWith('application/json')) {
fail(res, 415, 'json-required');
return undefined;
}
let parsed;
try {
parsed = JSON.parse(await readBody(req));
}
catch (error) {
fail(res, 400, error instanceof Error && error.message === 'request-too-large' ? 'request-too-large' : 'invalid-json');
return undefined;
}
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
fail(res, 400, 'invalid-body');
return undefined;
}
return parsed;
}
/** Last test run, kept in memory so the card can show "最后检查". */
let lastCheck = null;
/**
* 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;
/** The payload the page and the client card both consume. */
function statusPayload(deps) {
const view = deps.store.describe();
@ -67,6 +156,8 @@ function statusPayload(deps) {
const settings = {
enabled: view.enabled,
baseUrl: view.baseUrl,
baseUrlConfigured: view.baseUrlConfigured,
baseUrlOrigin: view.baseUrlOrigin,
clientId: view.clientId,
requestTimeoutMs: view.requestTimeoutMs,
defaultK: view.defaultK,
@ -76,7 +167,13 @@ function statusPayload(deps) {
skillsDir: view.skillsDir,
};
return {
ok: true, settings, tokens, settingsPath: view.statePath, reporter: deps.reporter.snapshot(),
ok: true,
settings,
tokens,
settingsPath: view.statePath,
reporter: deps.reporter.snapshot(),
lastCheck,
capabilities: capabilities(deps),
...(deps.skills === undefined ? {} : { skills: deps.skills() }),
};
}
@ -105,6 +202,14 @@ function serveStatus(deps, req, res) {
}
json(res, 200, statusPayload(deps));
}
/** `GET /dsh-brain/capabilities`. */
function serveCapabilities(deps, req, res) {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
json(res, 200, { ok: true, ...capabilities(deps) });
}
/** `PUT /dsh-brain/config`. */
async function serveConfig(deps, req, res) {
if (req.method !== 'PUT' && req.method !== 'POST') {
@ -137,9 +242,22 @@ async function serveConfig(deps, req, res) {
fail(res, 400, result.error ?? 'invalid-patch');
return;
}
json(res, 200, statusPayload(deps));
json(res, 200, {
...statusPayload(deps),
...(result.clearedTokens === undefined ? {} : { credentialsCleared: result.clearedTokens }),
});
}
/** `POST /dsh-brain/test` — validate both tokens without recording anything. */
/** Map one failed credential probe onto a check state. */
function checkState(error) {
if (error.status === 0)
return 'unreachable';
if (error.status === 401)
return 'invalid';
if (error.status === 403)
return 'forbidden';
return 'error';
}
/** `POST /dsh-brain/test` — read-only checks, one per credential. */
async function serveTest(deps, req, res) {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
@ -150,36 +268,67 @@ async function serveTest(deps, req, res) {
return;
}
const client = deps.client();
const checks = [];
const settings = deps.store.settings();
const reach = await client.reach();
checks.push({
id: 'network',
label: '服务地址',
state: reach.ok ? 'ok' : 'unreachable',
message: deps.store.describe().baseUrlConfigured === false ? '服务地址还是打包默认值,请先填写真实地址。' : reach.message,
});
const activityToken = deps.store.activityToken();
if (activityToken === '') {
checks.push({ id: 'activity', label: '活动上报权限(activity:write)', state: 'unconfigured', message: '未配置令牌' });
}
else {
const probe = await client.probeActivity(activityToken);
checks.push({
id: 'activity',
label: '活动上报权限(activity:write)',
state: probe.ok ? 'ok' : checkState(probe.error),
message: probe.ok ? '鉴权通过(只验证权限,不代表已写入一条上报)' : describeError(probe.error),
});
}
const memoryToken = deps.store.memoryToken();
const activity = activityToken === ''
? { ok: false, message: '还没填令牌:把 activity:write 密钥粘到下面「活动上报令牌」再点保存' }
: await (async () => {
const probe = await client.probeActivity(activityToken);
return probe.ok
? { ok: true, message: '令牌有效(鉴权通过)' }
: { ok: false, message: describeError(probe.error) };
})();
const memory = memoryToken === ''
? { ok: false, message: '还没填令牌:把 memory:write 密钥粘到下面「记忆读写令牌」再点保存' }
: await (async () => {
const probe = await client.projects();
return probe.ok
? { ok: true, message: `令牌有效(${(probe.data.projects ?? []).length} 个项目)` }
: { ok: false, message: describeError(probe.error) };
})();
if (memoryToken === '') {
checks.push({ id: 'memory', label: '记忆读写权限(memory:write)', state: 'unconfigured', message: '未配置令牌' });
}
else {
const probe = await client.projects();
checks.push({
id: 'memory',
label: '记忆读写权限(memory:write)',
state: probe.ok ? 'ok' : checkState(probe.error),
message: probe.ok ? `鉴权通过(${(probe.data.projects ?? []).length} 个项目)` : describeError(probe.error),
});
}
const summaryToken = deps.store.summaryToken();
const summary = !deps.store.settings().summaryEnabled
? { ok: false, message: '自动摘要已关闭(可在下方勾选开启)' }
: summaryToken === ''
? { ok: false, message: '未配置摘要令牌:留空则不做自动摘要' }
: await (async () => {
const probe = await client.probeSummary(summaryToken);
return probe.ok
? { ok: true, message: '摘要令牌有效(只进待确认队列)' }
: { ok: false, message: describeError(probe.error) };
})();
json(res, 200, { ok: true, activity, memory, summary });
if (!settings.summaryEnabled) {
checks.push({ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '自动摘要已关闭' });
}
else if (summaryToken === '') {
checks.push({ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '未配置摘要令牌(可选)' });
}
else {
const probe = await client.probeSummary(summaryToken);
checks.push({
id: 'summary',
label: '摘要权限(summary:write)',
state: probe.ok ? 'ok' : checkState(probe.error),
message: probe.ok ? '鉴权通过(只进待确认队列)' : describeError(probe.error),
});
}
lastCheck = { at: Date.now(), checks };
json(res, 200, {
ok: true,
checkedAt: lastCheck.at,
checks,
// Kept for the older card/page shape; both views read the same probes.
activity: { ok: checks[1]?.state === 'ok', message: checks[1]?.message ?? '' },
memory: { ok: checks[2]?.state === 'ok', message: checks[2]?.message ?? '' },
summary: { ok: checks[3]?.state === 'ok', message: checks[3]?.message ?? '' },
});
}
/** `POST /dsh-brain/flush`. */
async function serveFlush(deps, req, res) {
@ -194,7 +343,7 @@ async function serveFlush(deps, req, res) {
const result = await deps.reporter.flush();
json(res, 200, { ok: true, ...result });
}
/** Labels attached to the two tokens this plugin asks the dashboard to mint. */
/** Labels attached to the tokens this plugin asks the dashboard to mint. */
const TOKEN_LABELS = {
activity: 'DSH desktop 活动上报',
memory: 'DSH desktop 记忆读写',
@ -202,12 +351,12 @@ const TOKEN_LABELS = {
};
/**
* `POST /dsh-brain/login` — sign in with the cloud account and exchange it
* for the two scoped tokens.
* for the scoped tokens.
*
* The password is used once, in memory, and never written anywhere: the flow is
* password → short-lived session cookie → two `cmt_…` tokens → cookie dropped.
* Only the tokens are persisted, so a later password change does not break the
* plugin and revoking a token does not reveal the password.
* password → short-lived session cookie → tokens → cookie dropped. Only the
* tokens are persisted, so a later password change does not break the plugin
* and revoking a token does not reveal the password.
*/
async function serveLogin(deps, req, res) {
if (req.method !== 'POST') {
@ -304,28 +453,60 @@ function adminStatus(code) {
switch (code) {
case 'not_found': return 404;
case 'invalid_name':
case 'invalid_url': return 400;
case 'invalid_url':
case 'invalid_plan': return 400;
case 'collision':
case 'sync_running': return 409;
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 + trash)
* `POST /dsh-brain/skills/toggle` { folder, enabled }
* `POST /dsh-brain/skills/remove` { folder }
* `POST /dsh-brain/skills/install` { url }
* `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) {
if (deps.admin === undefined) {
const admin = deps.admin;
if (admin === undefined) {
fail(res, 404, 'skills-admin-unavailable');
return;
}
const admin = deps.admin;
const suffix = (req.url ?? '').split('?')[0]?.slice(ROUTES.skills.length) ?? '';
if (suffix === '' || suffix === '/') {
if (req.method !== 'GET' && req.method !== 'HEAD') {
@ -349,58 +530,433 @@ async function serveSkills(deps, req, res) {
fail(res, 405, 'method-not-allowed');
return;
}
json(res, 200, { ok: true, ...(await admin.list()) });
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 = {
'/toggle': async (body) => admin.setEnabled(body.folder, body.enabled === true),
'/remove': async (body) => admin.remove(body.folder),
'/install': async (body) => admin.installFromGit(body.url),
'/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)) };
},
};
const action = actions[suffix];
// 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 = {
'/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;
}
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
const body = await jsonBody(req, res);
if (body === undefined)
return;
}
if (!sameOrigin(req)) {
fail(res, 403, 'origin-rejected');
return;
}
const type = (req.headers['content-type'] ?? '').toLowerCase();
if (!type.startsWith('application/json')) {
fail(res, 415, 'json-required');
return;
}
let body;
try {
body = JSON.parse(await readBody(req));
}
catch {
fail(res, 400, 'invalid-json');
return;
}
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
fail(res, 400, 'invalid-body');
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;
}
else {
json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) });
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 '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(ROUTES.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) });
}
}
/**
* Sync surface:
* `GET /dsh-brain/sync/status` latest stats + both sides of each conflict
* `POST /dsh-brain/sync/run` trigger one pass now
* `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual }
*/
async function serveSync(deps, req, res) {
const sync = deps.sync;
if (sync === undefined) {
fail(res, 404, 'sync-unavailable');
return;
}
const url = new URL(req.url ?? '/', 'http://localhost');
const suffix = url.pathname.slice(ROUTES.sync.length);
try {
if (suffix === '' || suffix === '/' || suffix === '/status') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
json(res, 200, { ok: true, stats: sync.stats(), conflicts: await sync.conflictDetails() });
return;
}
if (suffix === '/run') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const stats = await sync.syncOnce();
json(res, 200, { ok: true, stats, conflicts: await sync.conflictDetails() });
return;
}
if (suffix === '/resolve') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const result = await sync.resolveConflict(body.name, body.action);
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() });
return;
}
fail(res, 404, 'unknown-sync-route');
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
const known = ['invalid_name', 'invalid_action', 'no_local_copy', 'no_cloud_copy', 'stale_revision', 'sync_running', 'manifest_mismatch'];
const code = known.includes(message) ? message : 'internal';
const status = code === 'internal' ? 500
: code === 'invalid_name' || code === 'invalid_action' ? 400
: 409;
json(res, status, { ok: false, code, error: message });
}
}
/** 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(ROUTES.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 });
}
}
/** dsh-brain data migration: GET status, POST run. */
async function serveMigrate(_deps, req, res) {
const url = new URL(req.url ?? '/', 'http://localhost');
const suffix = url.pathname.slice(ROUTES.migrate.length);
if (suffix === '' || suffix === '/' || suffix === '/brain') {
if (req.method === 'GET') {
const status = await brainStatus();
json(res, 200, { ok: true, ...status });
return;
}
if (req.method === 'POST') {
const result = await migrateLegacyFiles();
json(res, 200, { ok: true, ...result });
return;
}
fail(res, 405, 'method-not-allowed');
return;
}
fail(res, 404, 'unknown-migrate-route');
}
/** Build the exact-route table registered with the host web server. */
/** Pre-rename aliases (v0.5.0): the same handlers under the old `/cloud-memory` prefix. */
/** Pre-rename aliases (0.8.0): the same handlers under the old `/cloud-memory` prefix. */
export function createLegacyRoutes(deps) {
return createRoutes(deps).map((route) => ({ ...route, path: route.path.replace('/dsh-brain', '/cloud-memory') }));
}
@ -416,6 +972,11 @@ export function createRoutes(deps) {
path: ROUTES.status,
handler: (req, res) => serveStatus(deps, req, res),
},
{
kind: 'exact',
path: ROUTES.capabilities,
handler: (req, res) => serveCapabilities(deps, req, res),
},
{
kind: 'exact',
path: ROUTES.config,
@ -441,5 +1002,25 @@ export function createRoutes(deps) {
path: ROUTES.skills,
handler: (req, res) => serveSkills(deps, req, res),
},
{
kind: 'prefix',
path: ROUTES.market,
handler: (req, res) => serveMarket(deps, req, res),
},
{
kind: 'prefix',
path: ROUTES.sync,
handler: (req, res) => serveSync(deps, req, res),
},
{
kind: 'prefix',
path: ROUTES.clients,
handler: (req, res) => serveClients(deps, req, res),
},
{
kind: 'prefix',
path: ROUTES.migrate,
handler: (req, res) => serveMigrate(deps, req, res),
},
];
}