414 lines
16 KiB
JavaScript
414 lines
16 KiB
JavaScript
import { createSettingsUiRoutes } from "./settings-ui/routes.js";
|
||
import { serveDepartments } from "./settings-ui/departments-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',
|
||
localMemory: '/dsh-brain/local-memory',
|
||
departments: '/dsh-brain/departments',
|
||
};
|
||
/** Reported when the MCP sub-plugin entry is not applied; the client keeps the tab hidden. */
|
||
const MCP_UNAVAILABLE = {
|
||
bridge: 'unavailable',
|
||
notes: ['MCP 管理页未启用:dsh-brain-mcp 子插件已停用,可在宿主插件设置中开启。'],
|
||
};
|
||
/** What this build actually implements, stated per feature. */
|
||
function capabilities(deps) {
|
||
const marketProviders = deps.market?.list().length ?? 0;
|
||
const mcp = deps.mcp === true ? mcpCapability() : MCP_UNAVAILABLE;
|
||
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. */
|
||
export function buildStatusPayload(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,
|
||
localMemoryEnabled: view.localMemoryEnabled,
|
||
cloudMemoryEnabled: view.cloudMemoryEnabled,
|
||
autoMemorySpaces: view.autoMemorySpaces,
|
||
autoSummaryEnabled: view.autoSummaryEnabled,
|
||
autoProfileEnabled: view.autoProfileEnabled,
|
||
localMemoryK: view.localMemoryK,
|
||
};
|
||
return {
|
||
ok: true,
|
||
settings,
|
||
tokens,
|
||
settingsPath: view.statePath,
|
||
reporter: deps.reporter.snapshot(),
|
||
lastCheck: getLastCheck(),
|
||
capabilities: capabilities(deps),
|
||
bundles: deps.bundles ?? {},
|
||
...(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, buildStatusPayload(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, {
|
||
...buildStatusPayload(deps),
|
||
...(result.clearedTokens === undefined ? {} : { credentialsCleared: result.clearedTokens }),
|
||
});
|
||
}
|
||
/** Local memory management API: status/search/documents/backup/migration. */
|
||
async function serveLocalMemory(deps, req, res) {
|
||
const manager = deps.localMemory;
|
||
if (manager === undefined) {
|
||
fail(res, 503, 'local-memory-unavailable');
|
||
return;
|
||
}
|
||
const url = new URL(req.url ?? '/', 'http://localhost');
|
||
const marker = '/local-memory';
|
||
const markerAt = url.pathname.indexOf(marker);
|
||
const suffix = markerAt < 0 ? '' : url.pathname.slice(markerAt + marker.length);
|
||
if (suffix === '' || suffix === '/' || suffix === '/status') {
|
||
if (req.method !== 'GET') {
|
||
fail(res, 405, 'method-not-allowed');
|
||
return;
|
||
}
|
||
json(res, 200, { ok: true, ...(await manager.storageStatus()) });
|
||
return;
|
||
}
|
||
if (suffix === '/spaces') {
|
||
if (req.method !== 'GET') {
|
||
fail(res, 405, 'method-not-allowed');
|
||
return;
|
||
}
|
||
json(res, 200, { ok: true, spaces: await manager.projects() });
|
||
return;
|
||
}
|
||
if (suffix === '/documents') {
|
||
if (req.method !== 'GET') {
|
||
fail(res, 405, 'method-not-allowed');
|
||
return;
|
||
}
|
||
json(res, 200, { ok: true, documents: await manager.documents() });
|
||
return;
|
||
}
|
||
if (suffix === '/memories') {
|
||
if (req.method !== 'GET') {
|
||
fail(res, 405, 'method-not-allowed');
|
||
return;
|
||
}
|
||
const limit = Math.max(1, Math.min(1000, Number.parseInt(url.searchParams.get('limit') ?? '50', 10) || 50));
|
||
const offset = Math.max(0, Number.parseInt(url.searchParams.get('offset') ?? '0', 10) || 0);
|
||
const page = await manager.list({ limit, offset });
|
||
json(res, 200, { ok: true, total: page.total, items: page.items.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) });
|
||
return;
|
||
}
|
||
if (suffix === '/forget') {
|
||
if (req.method !== 'POST') {
|
||
fail(res, 405, 'method-not-allowed');
|
||
return;
|
||
}
|
||
if (!sameOrigin(req)) {
|
||
fail(res, 403, 'origin-rejected');
|
||
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;
|
||
}
|
||
const input = body;
|
||
const id = typeof input.id === 'string' ? input.id.trim() : '';
|
||
if (id === '') {
|
||
fail(res, 400, 'id-required');
|
||
return;
|
||
}
|
||
const expectedRevision = typeof input.expectedRevision === 'number' && Number.isFinite(input.expectedRevision) ? Math.trunc(input.expectedRevision) : undefined;
|
||
json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision) });
|
||
return;
|
||
}
|
||
if (suffix === '/search') {
|
||
if (req.method !== 'GET') {
|
||
fail(res, 405, 'method-not-allowed');
|
||
return;
|
||
}
|
||
const query = (url.searchParams.get('q') ?? '').trim();
|
||
if (query === '') {
|
||
fail(res, 400, 'query-required');
|
||
return;
|
||
}
|
||
const requested = Number.parseInt(url.searchParams.get('k') ?? '5', 10);
|
||
const k = Number.isFinite(requested) ? Math.max(1, Math.min(100, requested)) : 5;
|
||
const records = await manager.search(query, k);
|
||
json(res, 200, { ok: true, query, count: records.length, matches: records.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) });
|
||
return;
|
||
}
|
||
if (suffix === '/backup') {
|
||
if (req.method !== 'POST' || !sameOrigin(req)) {
|
||
fail(res, req.method !== 'POST' ? 405 : 403, req.method !== 'POST' ? 'method-not-allowed' : 'origin-rejected');
|
||
return;
|
||
}
|
||
json(res, 200, { ok: true, ...(await manager.createBackup()) });
|
||
return;
|
||
}
|
||
if (suffix === '/migrate') {
|
||
if (req.method === 'GET') {
|
||
const report = await manager.legacyMigrationReport();
|
||
json(res, 200, { ok: true, ...report });
|
||
return;
|
||
}
|
||
if (req.method !== 'POST') {
|
||
fail(res, 405, 'method-not-allowed');
|
||
return;
|
||
}
|
||
if (!sameOrigin(req)) {
|
||
fail(res, 403, 'origin-rejected');
|
||
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;
|
||
}
|
||
const input = body;
|
||
const action = typeof input.action === 'string' ? input.action : 'report';
|
||
if (action === 'report') {
|
||
const report = await manager.legacyMigrationReport();
|
||
json(res, 200, { ok: true, ...report });
|
||
return;
|
||
}
|
||
if (action === 'migrate') {
|
||
if (typeof input.path !== 'string' || input.path.trim() === '') {
|
||
fail(res, 400, 'path-required');
|
||
return;
|
||
}
|
||
json(res, 200, { ok: true, ...(await manager.migrateLegacy(input.path.trim())) });
|
||
return;
|
||
}
|
||
if (action === 'rollback') {
|
||
if (typeof input.copiedTo !== 'string' || input.copiedTo.trim() === '') {
|
||
fail(res, 400, 'copiedTo-required');
|
||
return;
|
||
}
|
||
const destination = typeof input.destination === 'string' && input.destination.trim() !== '' ? input.destination.trim() : undefined;
|
||
json(res, 200, { ok: true, ...(await manager.rollbackMigration(input.copiedTo.trim(), destination)) });
|
||
return;
|
||
}
|
||
fail(res, 400, 'unknown-action');
|
||
return;
|
||
}
|
||
fail(res, 404, 'unknown-local-memory-route');
|
||
}
|
||
/** 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 route objects under the old
|
||
* `/cloud-memory` prefix. Each sub-plugin entry aliases its own slice this
|
||
* way, so the legacy paths follow whatever subset is currently enabled.
|
||
*/
|
||
export function legacyAliases(routes) {
|
||
return routes.map((route) => ({ ...route, path: route.path.replace('/dsh-brain', '/cloud-memory') }));
|
||
}
|
||
/** The full legacy alias table for the compat root entry. */
|
||
export function createLegacyRoutes(deps) {
|
||
return legacyAliases(createRoutes(deps));
|
||
}
|
||
/**
|
||
* 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 }),
|
||
...createCoreRoutes(deps),
|
||
...createCloudSyncRoutes({
|
||
store: deps.store,
|
||
client: deps.client,
|
||
reporter: deps.reporter,
|
||
sync: deps.sync,
|
||
statusView: () => buildStatusPayload(deps),
|
||
}),
|
||
...createSkillRoutes({
|
||
version: deps.version,
|
||
admin: deps.admin,
|
||
groups: deps.groups,
|
||
market: deps.market,
|
||
updates: deps.updates,
|
||
clients: deps.clients,
|
||
}),
|
||
];
|
||
}
|
||
/**
|
||
* The core (non-bundle) routes: status, capabilities, config, and migrate.
|
||
* The settings-ui sub-plugin entry registers exactly these plus its page;
|
||
* the compat root aggregates them with the cloud-sync and skill bundles.
|
||
*/
|
||
export function createCoreRoutes(deps) {
|
||
return [
|
||
{
|
||
kind: 'prefix',
|
||
path: ROUTES.localMemory,
|
||
handler: (req, res) => serveLocalMemory(deps, req, res),
|
||
},
|
||
{
|
||
kind: 'prefix',
|
||
path: ROUTES.departments,
|
||
handler: (req, res) => serveDepartments(deps, req, res),
|
||
},
|
||
{
|
||
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),
|
||
},
|
||
{
|
||
kind: 'prefix',
|
||
path: ROUTES.migrate,
|
||
handler: (req, res) => serveMigrate(deps, req, res),
|
||
},
|
||
];
|
||
}
|