/** * HTTP surface served by the host web server. * * All routes live under `/dsh-brain`: * - `GET /dsh-brain` configuration page (HTML) * - `GET /dsh-brain/status` settings + reporter counters + capabilities * - `GET /dsh-brain/capabilities` what this build can and cannot do * - `PUT /dsh-brain/config` apply a settings patch * - `POST /dsh-brain/login` password sign-in, mints the tokens * - `POST /dsh-brain/test` read-only checks, per credential * - `POST /dsh-brain/flush` retry the queued reports * - `GET /dsh-brain/skills/api` skill inventory + pending plans * - `POST /dsh-brain/skills/*` detail / toggle / install plan / commit / uninstall * * Every JSON route is same-origin only: the tokens are read from the local file * and never echoed back, but a cross-site `PUT` could still be used to redirect * reports to an attacker's base URL, so the origin check stays on. * * Skill writes follow a plan → commit contract: a destructive operation is * never reachable in one request, and a client-supplied path is never trusted. */ import type { IncomingMessage, ServerResponse } from 'node:http' import type { CloudClient } from './api.ts' import type { SettingsStore, SettingsView, TokenView } from './store.ts' import type { Reporter } from './reporter.ts' import { createSettingsUiRoutes } from './settings-ui/routes.ts' import { serveDepartments } from './settings-ui/departments-routes.ts' import type { CloudMemoryWebRoute } from './context-types.ts' import type { LocalMemoryManager } from './local-memory/manager.ts' import type { DepartmentManager } from './local-memory/departments/index.ts' import type { SkillSync, SkillSyncStats } from './skill-sync.ts' import type { SkillAdmin } from './skill-admin.ts' import type { SkillGroupManager } from './skill-groups.ts' import type { MarketService } from './market.ts' import type { SkillUpdater } from './skill-update.ts' import type { ClientRegistry } from './clients.ts' import { brainStatus, migrateLegacyFiles } from './brain-migration.ts' import { mcpCapability, type McpCapability } from './mcp.ts' import { fail, json, readBody, sameOrigin } from './http.ts' import { createCloudSyncRoutes, getLastCheck } from './cloudsync-routes.ts' import { createSkillRoutes } from './skills/routes.ts' /** 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', } as const /** Everything the routes need from the plugin core. */ export interface RouteDeps { version: string store: SettingsStore reporter: Reporter client: () => CloudClient /** Latest skill-sync stats, when the engine is wired in. */ skills?: () => SkillSyncStats /** Local skill management (list / toggle / install / uninstall), when wired in. */ admin?: SkillAdmin /** Multi-source skill tree (sources, categories, per-group switches). */ groups?: SkillGroupManager /** Skill market providers (search / detail / resolve artifact). */ market?: MarketService /** The sync engine itself, for conflict details and interactive resolution. */ sync?: SkillSync /** Update / rollback over a recorded git or market source. */ updates?: SkillUpdater /** Cross-software / workspace inventory (v1.1 §15). */ clients?: ClientRegistry /** Whether the MCP sub-plugin entry is applied (gates the MCP tab). */ mcp?: boolean /** Local memory manager, when the memory bundle is available. */ localMemory?: LocalMemoryManager /** Department registry (P1.5), when wired in. */ departments?: DepartmentManager /** Bundle activation states reported to the total panel. */ bundles?: Record } /** One feature flag the card reads before it renders a control. */ export interface CapabilityReport { version: string features: { connection: boolean identitySwitch: boolean skills: boolean skillInstallPlans: boolean skillUninstallPlan: boolean skillsSync: boolean skillsMarketplace: boolean /** Market search/detail/install is wired to a real provider. */ marketProviders?: number /** Update/rollback is available for skills with a source record. */ skillUpdate?: boolean /** Interactive sync conflict resolution is available. */ syncResolve?: boolean /** Cross-software and workspace skill inventory is available. */ multiClient?: boolean /** dsh-brain data migration status (package rename stays a deploy step). */ brainMigration?: 'ready' | 'pending-deploy' mcpBridge: 'host-plugin' | 'unavailable' } notes: string[] } /** Reported when the MCP sub-plugin entry is not applied; the client keeps the tab hidden. */ const MCP_UNAVAILABLE: McpCapability = { bridge: 'unavailable', notes: ['MCP 管理页未启用:dsh-brain-mcp 子插件已停用,可在宿主插件设置中开启。'], } /** What this build actually implements, stated per feature. */ function capabilities(deps: RouteDeps): CapabilityReport { 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: RouteDeps): Record { const view: SettingsView = deps.store.describe() const tokens = { activity: view.activityToken as TokenView, memory: view.memoryToken as TokenView, summary: view.summaryToken as TokenView, } 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: RouteDeps, req: IncomingMessage, res: ServerResponse): void { if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed') return } json(res, 200, buildStatusPayload(deps)) } /** `GET /dsh-brain/capabilities`. */ function serveCapabilities(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): void { 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: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { 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: unknown 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 as Record) 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: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { 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: unknown 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 as Record 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: unknown 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 as Record 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: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { 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: CloudMemoryWebRoute[]): CloudMemoryWebRoute[] { 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: RouteDeps): CloudMemoryWebRoute[] { 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: RouteDeps): CloudMemoryWebRoute[] { 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: RouteDeps): CloudMemoryWebRoute[] { 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), }, ] }