dsh-brain/lib/routes.js

215 lines
7.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createSettingsUiRoutes } from "./settings-ui/routes.js";
import { brainStatus, migrateLegacyFiles } from "./brain-migration.js";
import { mcpCapability } from "./mcp.js";
import { fail, json, readBody, sameOrigin } from "./http.js";
import { createCloudSyncRoutes, getLastCheck } from "./cloudsync-routes.js";
import { createSkillRoutes } from "./skills/routes.js";
/** 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',
};
/** What this build actually implements, stated per feature. */
function capabilities(deps) {
const marketProviders = deps.market?.list().length ?? 0;
const mcp = mcpCapability();
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',
mcpBridge: mcp.bridge,
},
notes: [
...(deps.market === undefined
? ['技能市场未启用:没有配置市场来源。']
: [`技能市场已接入 ${marketProviders} 个来源;安装走暂存计划并固定提交。`]),
...(deps.updates === undefined
? ['技能更新/回退未启用。']
: ['更新/回退仅对带来源记录(.skill-source.json)的技能生效,更新前自动备份。']),
...(deps.sync === undefined ? [] : ['同步冲突可在技能页签逐项“保留本地 / 采用云端 / 手动合并”。']),
...(deps.clients === undefined ? [] : ['跨软件与工作区技能清单为只读(DSH 之外不写目录);dsh-brain 数据迁移已就绪,实际改名需部署重启。']),
...mcp.notes,
],
};
}
/** The payload the page and the client card both consume. */
function statusPayload(deps) {
const view = deps.store.describe();
const tokens = {
activity: view.activityToken,
memory: view.memoryToken,
summary: view.summaryToken,
};
const settings = {
enabled: view.enabled,
baseUrl: view.baseUrl,
baseUrlConfigured: view.baseUrlConfigured,
baseUrlOrigin: view.baseUrlOrigin,
clientId: view.clientId,
requestTimeoutMs: view.requestTimeoutMs,
defaultK: view.defaultK,
summaryEnabled: view.summaryEnabled,
summaryMaxChars: view.summaryMaxChars,
activityEnabled: view.activityEnabled,
memoryEnabled: view.memoryEnabled,
skillsSyncEnabled: view.skillsSyncEnabled,
skillsDir: view.skillsDir,
};
return {
ok: true,
settings,
tokens,
settingsPath: view.statePath,
reporter: deps.reporter.snapshot(),
lastCheck: getLastCheck(),
capabilities: capabilities(deps),
...(deps.skills === undefined ? {} : { skills: deps.skills() }),
};
}
/** `GET /dsh-brain/status`. */
function serveStatus(deps, req, res) {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
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') {
fail(res, 405, 'method-not-allowed');
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 patch;
try {
patch = JSON.parse(await readBody(req));
}
catch (error) {
fail(res, 400, error instanceof Error && error.message === 'request-too-large' ? 'request-too-large' : 'invalid-json');
return;
}
if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) {
fail(res, 400, 'invalid-patch');
return;
}
const result = deps.store.patch(patch);
if (!result.ok) {
fail(res, 400, result.error ?? 'invalid-patch');
return;
}
json(res, 200, {
...statusPayload(deps),
...(result.clearedTokens === undefined ? {} : { credentialsCleared: result.clearedTokens }),
});
}
/** 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');
}
/** 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') }));
}
/**
* Build the exact-route table registered with the host web server.
*
* Composition (m00001 §4): the root owns `/status` and `/capabilities`; the
* settings-ui bundle returns the page; the cloud-sync bundle returns
* login/test/flush/sync; the skill bundle returns skills/market/clients. No
* path shadows another, so the grouped registration order is safe.
*/
export function createRoutes(deps) {
return [
...createSettingsUiRoutes({ version: deps.version, store: deps.store }),
{
kind: 'exact',
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,
handler: (req, res) => serveConfig(deps, req, res),
},
...createCloudSyncRoutes({
store: deps.store,
client: deps.client,
reporter: deps.reporter,
sync: deps.sync,
statusView: () => statusPayload(deps),
}),
...createSkillRoutes({
version: deps.version,
admin: deps.admin,
groups: deps.groups,
market: deps.market,
updates: deps.updates,
clients: deps.clients,
}),
{
kind: 'prefix',
path: ROUTES.migrate,
handler: (req, res) => serveMigrate(deps, req, res),
},
];
}