diff --git a/cordis.patch.yml b/cordis.patch.yml index 31d9386..d15222c 100644 --- a/cordis.patch.yml +++ b/cordis.patch.yml @@ -1,13 +1,36 @@ -# dsh-brain bundle patch +# dsh-brain bundle patch — five toggleable sub-plugins. # -# Local-only build: this package is never published, so the row below is the +# Local-only build: this package is never published, so these rows are the # only way the plugin reaches the desktop profile tree. The host Loader -# resolves the row `name` as a package from the profile node_modules. +# resolves each row `name` as a subpath export of this package; all rows +# load in one process and share the kernel (src/kernel.ts), so each row +# only registers its own routes / tools / timers. +# +# Toggling: the host Settings → Plugins page (and dshmarket) write +# `- id: / disabled: true` lines into the profile patch, keyed by row +# id. Settings themselves persist in $DSH_HOME/dsh-brain.json; the seed +# config below only matters on first boot, so the rows stay safe to toggle +# in any order. +# +# Do NOT copy this insert block into the profile's cordis.patch.yml — +# duplicating entry ids breaks the Settings page. Keep overrides as +# top-level `- id: ` rows only. +# +# The compat root export (`.`) stays for older single-row profiles: it +# applies all five entries at once. - insert: - - id: dsh-brain - name: 'dsh-brain' + - id: dsh-brain-cloudsync + name: dsh-brain/cloudsync config: enabled: true baseUrl: https://your-memory-host/api/longmemory clientId: dsh-desktop skillsSyncEnabled: true + - id: dsh-brain-memory + name: dsh-brain/memory + - id: dsh-brain-skills + name: dsh-brain/skills + - id: dsh-brain-mcp + name: dsh-brain/mcp + - id: dsh-brain-settings-ui + name: dsh-brain/settings-ui diff --git a/lib/entries/cloudsync.js b/lib/entries/cloudsync.js new file mode 100644 index 0000000..a1cc59c --- /dev/null +++ b/lib/entries/cloudsync.js @@ -0,0 +1,66 @@ +import { brainKernel, VERSION } from "../kernel.js"; +import { buildStatusPayload, legacyAliases } from "../routes.js"; +import { createCloudSyncRoutes } from "../cloudsync-routes.js"; +export const name = 'dsh-brain-cloudsync'; +/** Services required before `apply` runs. */ +export const inject = ['webServer']; +/** How often the skill directory is reconciled with the cloud center. */ +const SKILL_SYNC_INTERVAL_MS = 15 * 60_000; +/** How often queued reports are retried. */ +const RETRY_INTERVAL_MS = 30_000; +/** Register the sub-plugin with the host. */ +export function apply(ctx, config) { + const logger = ctx.logger('dsh-brain'); + const kernel = brainKernel(config, logger); + kernel.activate('cloudsync'); + ctx.effect(() => () => kernel.deactivate('cloudsync'), 'dsh-brain-cloudsync: activation'); + // The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a + // third-party bundle cannot rely on; bind the listener through a local shape. + const onEvent = ctx.on; + ctx.effect(() => onEvent('session/event', (session, event) => { + try { + kernel.reporter.handleEvent(session, event); + } + catch (error) { + logger.warn(`turn event handling failed: ${error instanceof Error ? error.message : String(error)}`); + } + }), 'dsh-brain-cloudsync: turn reporting'); + ctx.effect(() => { + const timer = setInterval(() => { + if (kernel.store.activityToken() !== '' && kernel.settings().activityEnabled) { + void kernel.reporter.flush().catch((error) => { + logger.warn(`retry flush failed: ${error instanceof Error ? error.message : String(error)}`); + }); + } + }, RETRY_INTERVAL_MS); + timer.unref?.(); + return () => clearInterval(timer); + }, 'dsh-brain-cloudsync: retry timer'); + ctx.effect(() => { + const run = () => { + if (kernel.store.memoryToken() !== '') + void kernel.skillSync.syncOnce().catch(() => { }); + }; + const first = setTimeout(run, 5_000); + first.unref?.(); + const timer = setInterval(run, SKILL_SYNC_INTERVAL_MS); + timer.unref?.(); + return () => { clearTimeout(first); clearInterval(timer); }; + }, 'dsh-brain-cloudsync: skill sync timer'); + const webServer = ctx.webServer; + if (webServer === undefined) { + logger.warn('webServer service unavailable; cloud-sync routes stay disabled'); + return; + } + const routes = createCloudSyncRoutes({ + store: kernel.store, + client: () => kernel.client, + reporter: kernel.reporter, + sync: kernel.skillSync, + statusView: () => buildStatusPayload(kernel.routeDeps()), + }); + routes.push(...legacyAliases(routes)); + for (const route of routes) { + ctx.effect(() => webServer.register(route), `dsh-brain-cloudsync: route ${route.path}`); + } +} diff --git a/lib/entries/mcp.js b/lib/entries/mcp.js new file mode 100644 index 0000000..0f13d7a --- /dev/null +++ b/lib/entries/mcp.js @@ -0,0 +1,10 @@ +import { brainKernel } from "../kernel.js"; +export const name = 'dsh-brain-mcp'; +/** Services required before `apply` runs (none: activation only). */ +export const inject = []; +/** Register the sub-plugin with the host. */ +export function apply(ctx, config) { + const kernel = brainKernel(config, ctx.logger('dsh-brain')); + kernel.activate('mcp'); + ctx.effect(() => () => kernel.deactivate('mcp'), 'dsh-brain-mcp: activation'); +} diff --git a/lib/entries/memory.js b/lib/entries/memory.js new file mode 100644 index 0000000..b4c359d --- /dev/null +++ b/lib/entries/memory.js @@ -0,0 +1,19 @@ +import { brainKernel } from "../kernel.js"; +import { createMemoryTools } from "../memory/tools.js"; +export const name = 'dsh-brain-memory'; +/** Services required before `apply` runs. */ +export const inject = ['tools']; +/** Register the sub-plugin with the host. */ +export function apply(ctx, config) { + const kernel = brainKernel(config, ctx.logger('dsh-brain')); + kernel.activate('memory'); + ctx.effect(() => () => kernel.deactivate('memory'), 'dsh-brain-memory: activation'); + ctx.inject(['tools'], (toolsCtx) => { + const tools = toolsCtx.tools; + if (tools === undefined) + return; + for (const tool of createMemoryTools(kernel.toolDeps())) { + toolsCtx.effect(() => tools.register(tool), `dsh-brain-memory: tool ${tool.name}`); + } + }); +} diff --git a/lib/entries/settings-ui.js b/lib/entries/settings-ui.js new file mode 100644 index 0000000..a250fbd --- /dev/null +++ b/lib/entries/settings-ui.js @@ -0,0 +1,26 @@ +import { brainKernel, VERSION } from "../kernel.js"; +import { createCoreRoutes, legacyAliases } from "../routes.js"; +import { createSettingsUiRoutes } from "../settings-ui/routes.js"; +export const name = 'dsh-brain-settings-ui'; +/** Services required before `apply` runs. */ +export const inject = ['webServer']; +/** Register the sub-plugin with the host. */ +export function apply(ctx, config) { + const logger = ctx.logger('dsh-brain'); + const kernel = brainKernel(config, logger); + kernel.activate('settings-ui'); + ctx.effect(() => () => kernel.deactivate('settings-ui'), 'dsh-brain-settings-ui: activation'); + const webServer = ctx.webServer; + if (webServer === undefined) { + logger.warn('webServer service unavailable; the configuration page stays disabled'); + return; + } + const routes = [ + ...createSettingsUiRoutes({ version: VERSION, store: kernel.store }), + ...createCoreRoutes(kernel.routeDeps()), + ]; + routes.push(...legacyAliases(routes)); + for (const route of routes) { + ctx.effect(() => webServer.register(route), `dsh-brain-settings-ui: route ${route.path}`); + } +} diff --git a/lib/entries/skills.js b/lib/entries/skills.js new file mode 100644 index 0000000..2658ac2 --- /dev/null +++ b/lib/entries/skills.js @@ -0,0 +1,39 @@ +import { brainKernel, VERSION } from "../kernel.js"; +import { legacyAliases } from "../routes.js"; +import { createSkillRoutes } from "../skills/routes.js"; +import { createSkillTools } from "../tools.js"; +export const name = 'dsh-brain-skills'; +/** Services required before `apply` runs. */ +export const inject = ['tools', 'webServer']; +/** Register the sub-plugin with the host. */ +export function apply(ctx, config) { + const logger = ctx.logger('dsh-brain'); + const kernel = brainKernel(config, logger); + kernel.activate('skills'); + ctx.effect(() => () => kernel.deactivate('skills'), 'dsh-brain-skills: activation'); + ctx.inject(['tools'], (toolsCtx) => { + const tools = toolsCtx.tools; + if (tools === undefined) + return; + for (const tool of createSkillTools(kernel.toolDeps())) { + toolsCtx.effect(() => tools.register(tool), `dsh-brain-skills: tool ${tool.name}`); + } + }); + const webServer = ctx.webServer; + if (webServer === undefined) { + logger.warn('webServer service unavailable; skill routes stay disabled'); + return; + } + const routes = createSkillRoutes({ + version: VERSION, + admin: kernel.skillAdmin, + groups: kernel.skillGroups, + market: kernel.market, + updates: kernel.updater, + clients: kernel.clients, + }); + routes.push(...legacyAliases(routes)); + for (const route of routes) { + ctx.effect(() => webServer.register(route), `dsh-brain-skills: route ${route.path}`); + } +} diff --git a/lib/index.js b/lib/index.js index 45cea8b..ac713fa 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,193 +1,17 @@ -/** - * Plugin entry — host half. - * - * Responsibilities: - * 1. report one activity record per finished conversation round, - * 2. expose the memory tools to the agent, - * 3. serve the configuration page under `/dsh-brain` (legacy `/cloud-memory` routes stay as aliases). - * - * Everything registers through `ctx.effect(...)` so a plugin reload tears down - * its routes, timer, listeners, and tools without leftovers. - */ -import { CloudClient } from "./api.js"; -import { Reporter } from "./reporter.js"; -import { createLegacyRoutes, createRoutes } from "./routes.js"; -import { join, resolve } from 'node:path'; -import { SettingsStore, dshHome } from "./store.js"; -import { SkillSync } from "./skill-sync.js"; -import { SkillAdmin, skillsHoldingDir } from "./skill-admin.js"; -import { AdminSkillRepository } from "./skills/repository.js"; -import { SkillGroupManager, detectSources } from "./skill-groups.js"; -import { ClaudePluginMarketplaceProvider, MarketService } from "./market.js"; -import { SkillUpdater } from "./skill-update.js"; -import { ClientRegistry } from "./clients.js"; -import { createCloudMemoryRemoteFactory } from "./cloudsync.js"; -import { createMemoryTools } from "./memory/tools.js"; -import { createSkillTools } from "./tools.js"; +import * as cloudsync from "./entries/cloudsync.js"; +import * as memory from "./entries/memory.js"; +import * as skills from "./entries/skills.js"; +import * as mcp from "./entries/mcp.js"; +import * as settingsUi from "./entries/settings-ui.js"; /** Package name; also the client bundle id. */ export const name = 'dsh-brain'; /** Services required before `apply` runs. */ export const inject = ['webServer']; -/** Version reported by the status card. */ -const VERSION = '0.9.10'; -/** How often the skill directory is reconciled with the cloud center. */ -const SKILL_SYNC_INTERVAL_MS = 15 * 60_000; -/** How often queued reports are retried. */ -const RETRY_INTERVAL_MS = 30_000; -/** Register the plugin with the host. */ +/** Register the plugin with the host: all five sub-entries at once. */ export function apply(ctx, config) { - const logger = ctx.logger('dsh-brain'); - const store = new SettingsStore(config); - const settings = () => store.settings(); - // One client per instance; the settings closures keep it live across edits. - const client = new CloudClient({ - baseUrl: () => settings().baseUrl, - token: () => store.memoryToken(), - timeoutMs: () => settings().requestTimeoutMs, - }); - // The memory bundle sees the cloud through this factory only: the concrete - // client stays a cloud-sync concern, injected here at the composition root. - const memoryRemoteFactory = createCloudMemoryRemoteFactory({ - settings: () => settings(), - memoryToken: () => store.memoryToken(), - }); - const reporter = new Reporter({ - client, - settings: () => ({ enabled: settings().activityEnabled, clientId: settings().clientId }), - activityToken: () => store.activityToken(), - summary: () => ({ enabled: settings().summaryEnabled, maxChars: settings().summaryMaxChars }), - summaryToken: () => store.summaryToken(), - log: (message) => logger.warn(message), - }); - // The skill bundle owns its folders; the composition root only wires the - // shared root path and the parking area. The sync engine touches folders - // exclusively through AdminSkillRepository below. - const skillsRootDir = () => { - const dir = settings().skillsDir; - return dir !== '' ? resolve(dir) : join(dshHome(), 'skills'); - }; - // Built before the sync engine: the gate closure below dereferences - // skillSync lazily, so the TDZ order here is safe. - const skillAdmin = new SkillAdmin({ - skillsRoot: skillsRootDir, - holdingDir: () => skillsHoldingDir(), - gate: () => skillSync, - log: (message) => logger.info(message), - }); - // The skill bundle's public repository: the only door the cloud-sync - // engine has into skill folders. - const skillRepository = new AdminSkillRepository({ - admin: skillAdmin, - skillsRoot: skillsRootDir, - holdingDir: () => skillsHoldingDir(), - }); - const skillSync = new SkillSync({ - client: () => client, - settings: () => ({ - enabled: settings().enabled, - skillsSyncEnabled: settings().skillsSyncEnabled, - }), - repository: () => skillRepository, - log: (message) => logger.info(message), - }); - // The tree's sources are detected per call so a directory created while the - // process runs shows up on the next refresh. - const skillGroups = new SkillGroupManager({ - sources: () => detectSources(), - admin: skillAdmin, - log: (message) => logger.info(message), - }); - // One verified market source to start with: the Claude Code plugin marketplace - // manifest that Anthropic publishes. Entry ids never carry a URL, so the card - // cannot make the host fetch an arbitrary repository. - const market = new MarketService([ - new ClaudePluginMarketplaceProvider({ - id: 'anthropic-skills', - label: 'Anthropic Agent Skills', - description: 'Anthropic 公开的 Claude 技能市场(.claude-plugin/marketplace.json)', - repo: 'anthropics/skills', - ref: 'main', - }), - ]); - const updater = new SkillUpdater({ - admin: skillAdmin, - skillsRoot: skillsRootDir, - holdingDir: () => skillsHoldingDir(), - gate: () => skillSync, - log: (message) => logger.info(message), - }); - // Cross-software / workspace inventory. Read-only for every client except DSH. - const clients = new ClientRegistry(); - // Announce at most once per activation so a missing token is obvious in logs. - const effective = settings(); - if (!effective.activityEnabled) { - logger.info('turn reporting disabled by settings'); - } - else if (store.activityToken() === '') { - logger.warn(`reporting enabled but no activity token; configure one at ${store.path} or open /dsh-brain`); - } - else { - logger.info(`reporting to ${effective.baseUrl} as ${effective.clientId}`); - } - if (effective.summaryEnabled && store.summaryToken() === '') { - logger.info('turn summaries are enabled but no summary token is configured; nothing will be staged'); - } - // The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a - // third-party bundle cannot rely on; bind the listener through a local shape. - const onEvent = ctx.on; - ctx.effect(() => onEvent('session/event', (session, event) => { - try { - reporter.handleEvent(session, event); - } - catch (error) { - logger.warn(`turn event handling failed: ${error instanceof Error ? error.message : String(error)}`); - } - }), 'dsh-brain: turn reporting'); - ctx.inject(['tools'], (toolsCtx) => { - const tools = toolsCtx.tools; - if (tools === undefined) - return; - const toolDeps = { - remote: () => memoryRemoteFactory.current(), - client: () => client, - memoryToken: () => store.memoryToken(), - settings: () => ({ enabled: settings().memoryEnabled, defaultK: settings().defaultK }), - }; - for (const tool of [...createMemoryTools(toolDeps), ...createSkillTools(toolDeps)]) { - toolsCtx.effect(() => tools.register(tool), `dsh-brain: tool ${tool.name}`); - } - }); - const webServer = ctx.webServer; - if (webServer === undefined) { - logger.warn('webServer service unavailable; the configuration page stays disabled'); - } - else { - const routes = createRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin, groups: skillGroups, market, sync: skillSync, updates: updater, clients }); - routes.push(...createLegacyRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin, groups: skillGroups, market, sync: skillSync, updates: updater, clients })); - for (const route of routes) { - ctx.effect(() => webServer.register(route), `dsh-brain: route ${route.path}`); - } - } - ctx.effect(() => { - const timer = setInterval(() => { - if (store.activityToken() !== '' && settings().activityEnabled) { - void reporter.flush().catch((error) => { - logger.warn(`retry flush failed: ${error instanceof Error ? error.message : String(error)}`); - }); - } - }, RETRY_INTERVAL_MS); - timer.unref?.(); - return () => clearInterval(timer); - }, 'dsh-brain: retry timer'); - ctx.effect(() => { - const run = () => { - if (store.memoryToken() !== '') - void skillSync.syncOnce().catch(() => { }); - }; - const first = setTimeout(run, 5_000); - first.unref?.(); - const timer = setInterval(run, SKILL_SYNC_INTERVAL_MS); - timer.unref?.(); - return () => { clearTimeout(first); clearInterval(timer); }; - }, 'dsh-brain: skill sync timer'); + cloudsync.apply(ctx, config); + memory.apply(ctx, config); + skills.apply(ctx, config); + mcp.apply(ctx, config); + settingsUi.apply(ctx, config); } diff --git a/lib/kernel.js b/lib/kernel.js new file mode 100644 index 0000000..a43f6d3 --- /dev/null +++ b/lib/kernel.js @@ -0,0 +1,213 @@ +/** + * Shared kernel for the dsh-brain sub-plugins. + * + * The five bundle entries (dsh-brain/cloudsync, dsh-brain/memory, + * dsh-brain/skills, dsh-brain/mcp, dsh-brain/settings-ui) and the compat + * root entry all load from the same package inside the same host process, + * so this module's export resolves to a single instance: whichever entry + * applies first builds the services, the rest reuse them. + * + * The kernel holds service OBJECTS only. Routes, tools, timers, and the + * session listener belong to the entry that registers them through its own + * `ctx.effect(...)`, so toggling a sub-plugin off in the host plugin + * settings tears down exactly that slice and nothing else. `routeDeps()` + * assembles the RouteDeps view from the currently active bundles, which is + * how `/status` and `/capabilities` report what is actually enabled. + * + * Settings persist in `$DSH_HOME/dsh-brain.json`; the row config each + * entry receives is only the first-boot seed, so any entry may seed the + * kernel without diverging. + */ +import { join, resolve } from 'node:path'; +import { CloudClient } from "./api.js"; +import { createCloudMemoryRemoteFactory } from "./cloudsync.js"; +import { ClientRegistry } from "./clients.js"; +import { ClaudePluginMarketplaceProvider, MarketService } from "./market.js"; +import { Reporter } from "./reporter.js"; +import { SkillAdmin, skillsHoldingDir } from "./skill-admin.js"; +import { SkillGroupManager, detectSources } from "./skill-groups.js"; +import { SkillSync } from "./skill-sync.js"; +import { SkillUpdater } from "./skill-update.js"; +import { SettingsStore, dshHome } from "./store.js"; +import { AdminSkillRepository } from "./skills/repository.js"; +/** Version reported by the status card. */ +export const VERSION = '0.9.11'; +/** The shared service set behind every dsh-brain sub-plugin entry. */ +export class BrainKernel { + active = new Set(); + settingsOf; + store; + client; + memoryRemoteFactory; + reporter; + skillAdmin; + skillRepository; + skillSync; + skillGroups; + market; + updater; + clients; + constructor(config, logger) { + const store = new SettingsStore(config); + this.store = store; + const settings = () => store.settings(); + this.settingsOf = settings; + // One client per instance; the settings closures keep it live across edits. + const client = new CloudClient({ + baseUrl: () => settings().baseUrl, + token: () => store.memoryToken(), + timeoutMs: () => settings().requestTimeoutMs, + }); + this.client = client; + // The memory bundle sees the cloud through this factory only: the concrete + // client stays a cloud-sync concern, injected here at the composition root. + this.memoryRemoteFactory = createCloudMemoryRemoteFactory({ + settings: () => settings(), + memoryToken: () => store.memoryToken(), + }); + this.reporter = new Reporter({ + client, + settings: () => ({ enabled: settings().activityEnabled, clientId: settings().clientId }), + activityToken: () => store.activityToken(), + summary: () => ({ enabled: settings().summaryEnabled, maxChars: settings().summaryMaxChars }), + summaryToken: () => store.summaryToken(), + log: (message) => logger.warn(message), + }); + // The skill bundle owns its folders; the kernel only wires the shared root + // path and the parking area. The sync engine touches folders exclusively + // through AdminSkillRepository below. + const skillsRootDir = () => { + const dir = settings().skillsDir; + return dir !== '' ? resolve(dir) : join(dshHome(), 'skills'); + }; + // Built before the sync engine: the gate closures dereference skillSync + // lazily, so the TDZ order here is safe. + const skillAdmin = new SkillAdmin({ + skillsRoot: skillsRootDir, + holdingDir: () => skillsHoldingDir(), + gate: () => this.skillSync, + log: (message) => logger.info(message), + }); + this.skillAdmin = skillAdmin; + this.skillRepository = new AdminSkillRepository({ + admin: skillAdmin, + skillsRoot: skillsRootDir, + holdingDir: () => skillsHoldingDir(), + }); + this.skillSync = new SkillSync({ + client: () => client, + settings: () => ({ + enabled: settings().enabled, + skillsSyncEnabled: settings().skillsSyncEnabled, + }), + repository: () => this.skillRepository, + log: (message) => logger.info(message), + }); + // The tree's sources are detected per call so a directory created while + // the process runs shows up on the next refresh. + this.skillGroups = new SkillGroupManager({ + sources: () => detectSources(), + admin: skillAdmin, + log: (message) => logger.info(message), + }); + // One verified market source to start with: the Claude Code plugin + // marketplace manifest that Anthropic publishes. Entry ids never carry a + // URL, so the card cannot make the host fetch an arbitrary repository. + this.market = new MarketService([ + new ClaudePluginMarketplaceProvider({ + id: 'anthropic-skills', + label: 'Anthropic Agent Skills', + description: 'Anthropic 公开的 Claude 技能市场(.claude-plugin/marketplace.json)', + repo: 'anthropics/skills', + ref: 'main', + }), + ]); + this.updater = new SkillUpdater({ + admin: skillAdmin, + skillsRoot: skillsRootDir, + holdingDir: () => skillsHoldingDir(), + gate: () => this.skillSync, + log: (message) => logger.info(message), + }); + // Cross-software / workspace inventory. Read-only for every client but DSH. + this.clients = new ClientRegistry(); + // Announce at most once per kernel so a missing token is obvious in logs. + const effective = settings(); + if (!effective.activityEnabled) { + logger.info('turn reporting disabled by settings'); + } + else if (store.activityToken() === '') { + logger.warn(`reporting enabled but no activity token; configure one at ${store.path} or open /dsh-brain`); + } + else { + logger.info(`reporting to ${effective.baseUrl} as ${effective.clientId}`); + } + if (effective.summaryEnabled && store.summaryToken() === '') { + logger.info('turn summaries are enabled but no summary token is configured; nothing will be staged'); + } + } + /** Current settings snapshot (live: re-read on every call). */ + settings() { + return this.settingsOf(); + } + /** Mark a bundle's entry as applied; feeds `routeDeps()` gating. */ + activate(bundle) { + this.active.add(bundle); + } + /** Drop a bundle from the active set (entry teardown). */ + deactivate(bundle) { + this.active.delete(bundle); + } + /** Whether a bundle's entry is currently applied. */ + isActive(bundle) { + return this.active.has(bundle); + } + /** Tool deps shared by the memory and skill entries. */ + toolDeps() { + const store = this.store; + const settings = this.settingsOf; + return { + remote: () => this.memoryRemoteFactory.current(), + client: () => this.client, + memoryToken: () => store.memoryToken(), + settings: () => ({ enabled: settings().memoryEnabled, defaultK: settings().defaultK }), + }; + } + /** + * RouteDeps assembled from the currently active bundles: the status card + * then reports exactly what is on, not what this build could do. + */ + routeDeps() { + const skills = this.isActive('skills'); + const cloudsync = this.isActive('cloudsync'); + return { + version: VERSION, + store: this.store, + reporter: this.reporter, + client: () => this.client, + skills: cloudsync ? () => this.skillSync.stats() : undefined, + admin: skills ? this.skillAdmin : undefined, + groups: skills ? this.skillGroups : undefined, + market: skills ? this.market : undefined, + sync: cloudsync ? this.skillSync : undefined, + updates: skills ? this.updater : undefined, + clients: skills ? this.clients : undefined, + mcp: this.isActive('mcp'), + }; + } +} +let instance; +/** + * The process-wide kernel. The first entry to apply builds it (seeding from + * that row's config; the sidecar file is authoritative afterwards); every + * later entry — and the compat root — reuses the same instance. + */ +export function brainKernel(config, logger) { + if (instance === undefined) + instance = new BrainKernel(config, logger); + return instance; +} +/** Test hook: drop the singleton so the next call rebuilds it. */ +export function resetBrainKernel() { + instance = undefined; +} diff --git a/lib/routes.js b/lib/routes.js index deb9cd6..682c151 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -19,10 +19,15 @@ export const ROUTES = { clients: '/dsh-brain/clients', migrate: '/dsh-brain/migrate', }; +/** 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 = mcpCapability(); + const mcp = deps.mcp === true ? mcpCapability() : MCP_UNAVAILABLE; return { version: deps.version, features: { @@ -54,7 +59,7 @@ function capabilities(deps) { }; } /** The payload the page and the client card both consume. */ -function statusPayload(deps) { +export function buildStatusPayload(deps) { const view = deps.store.describe(); const tokens = { activity: view.activityToken, @@ -93,7 +98,7 @@ function serveStatus(deps, req, res) { fail(res, 405, 'method-not-allowed'); return; } - json(res, 200, statusPayload(deps)); + json(res, 200, buildStatusPayload(deps)); } /** `GET /dsh-brain/capabilities`. */ function serveCapabilities(deps, req, res) { @@ -136,7 +141,7 @@ async function serveConfig(deps, req, res) { return; } json(res, 200, { - ...statusPayload(deps), + ...buildStatusPayload(deps), ...(result.clearedTokens === undefined ? {} : { credentialsCleared: result.clearedTokens }), }); } @@ -160,9 +165,17 @@ async function serveMigrate(_deps, req, res) { } fail(res, 404, 'unknown-migrate-route'); } -/** Pre-rename aliases (0.8.0): the same handlers under the old `/cloud-memory` prefix. */ +/** + * 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 createRoutes(deps).map((route) => ({ ...route, path: route.path.replace('/dsh-brain', '/cloud-memory') })); + return legacyAliases(createRoutes(deps)); } /** * Build the exact-route table registered with the host web server. @@ -175,6 +188,31 @@ export function createLegacyRoutes(deps) { 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: 'exact', path: ROUTES.status, @@ -190,21 +228,6 @@ export function createRoutes(deps) { 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, diff --git a/package.json b/package.json index be380e9..6d6794f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-brain", - "version": "0.9.10", + "version": "0.9.11", "description": "Cloud memory for DSH: report one activity turn per conversation round and expose memory_search / memory_read / memory_add tools against a LongMemory cloud endpoint.", "type": "module", "license": "MIT", @@ -8,6 +8,11 @@ "exports": { ".": "./lib/index.js", "./client": "./client/index.js", + "./cloudsync": "./lib/entries/cloudsync.js", + "./memory": "./lib/entries/memory.js", + "./skills": "./lib/entries/skills.js", + "./mcp": "./lib/entries/mcp.js", + "./settings-ui": "./lib/entries/settings-ui.js", "./cordis.patch.yml": "./cordis.patch.yml", "./package.json": "./package.json", "./mnemon-provider": "./lib/mnemon/index.js" diff --git a/src/entries/cloudsync.ts b/src/entries/cloudsync.ts new file mode 100644 index 0000000..fbc2724 --- /dev/null +++ b/src/entries/cloudsync.ts @@ -0,0 +1,91 @@ +/** + * Cloud-sync sub-plugin entry — the connection half of dsh-brain. + * + * Owns: the session-event listener that stages activity reports, the retry + * and skill-sync timers, and the login / test / flush / sync routes (plus + * their legacy /cloud-memory aliases). Disabling this sub-plugin stops + * cloud traffic: no reports, no skill sync, no credential minting — but + * memory tools, skill management, and the settings page keep working off + * the shared kernel objects. + */ +import type { CloudMemoryContext, SessionEventLike, SessionLike } from '../context-types.ts' +import { brainKernel, VERSION } from '../kernel.ts' +import { buildStatusPayload, legacyAliases } from '../routes.ts' +import { createCloudSyncRoutes } from '../cloudsync-routes.ts' + +export const name = 'dsh-brain-cloudsync' + +/** Services required before `apply` runs. */ +export const inject = ['webServer'] + +/** How often the skill directory is reconciled with the cloud center. */ +const SKILL_SYNC_INTERVAL_MS = 15 * 60_000 + +/** How often queued reports are retried. */ +const RETRY_INTERVAL_MS = 30_000 + +/** Register the sub-plugin with the host. */ +export function apply(ctx: CloudMemoryContext, config: unknown): void { + const logger = ctx.logger('dsh-brain') + const kernel = brainKernel(config, logger) + kernel.activate('cloudsync') + ctx.effect(() => () => kernel.deactivate('cloudsync'), 'dsh-brain-cloudsync: activation') + + // The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a + // third-party bundle cannot rely on; bind the listener through a local shape. + const onEvent = ctx.on as unknown as ( + name: 'session/event', + listener: (session: SessionLike, event: SessionEventLike) => void, + ) => () => void + + ctx.effect( + () => onEvent('session/event', (session, event) => { + try { + kernel.reporter.handleEvent(session, event) + } catch (error) { + logger.warn(`turn event handling failed: ${error instanceof Error ? error.message : String(error)}`) + } + }), + 'dsh-brain-cloudsync: turn reporting', + ) + + ctx.effect(() => { + const timer = setInterval(() => { + if (kernel.store.activityToken() !== '' && kernel.settings().activityEnabled) { + void kernel.reporter.flush().catch((error: unknown) => { + logger.warn(`retry flush failed: ${error instanceof Error ? error.message : String(error)}`) + }) + } + }, RETRY_INTERVAL_MS) + timer.unref?.() + return () => clearInterval(timer) + }, 'dsh-brain-cloudsync: retry timer') + + ctx.effect(() => { + const run = () => { + if (kernel.store.memoryToken() !== '') void kernel.skillSync.syncOnce().catch(() => {}) + } + const first = setTimeout(run, 5_000) + first.unref?.() + const timer = setInterval(run, SKILL_SYNC_INTERVAL_MS) + timer.unref?.() + return () => { clearTimeout(first); clearInterval(timer) } + }, 'dsh-brain-cloudsync: skill sync timer') + + const webServer = ctx.webServer + if (webServer === undefined) { + logger.warn('webServer service unavailable; cloud-sync routes stay disabled') + return + } + const routes = createCloudSyncRoutes({ + store: kernel.store, + client: () => kernel.client, + reporter: kernel.reporter, + sync: kernel.skillSync, + statusView: () => buildStatusPayload(kernel.routeDeps()), + }) + routes.push(...legacyAliases(routes)) + for (const route of routes) { + ctx.effect(() => webServer.register(route), `dsh-brain-cloudsync: route ${route.path}`) + } +} diff --git a/src/entries/mcp.ts b/src/entries/mcp.ts new file mode 100644 index 0000000..07d15f6 --- /dev/null +++ b/src/entries/mcp.ts @@ -0,0 +1,24 @@ +/** + * MCP sub-plugin entry — the host half of the MCP management tab. + * + * The MCP feature is a browser bridge: the client tab talks to the host + * dsh-mcp-connector plugin, and this entry only contributes the + * capability fragment that makes `/dsh-brain/status` report + * `mcpBridge: 'host-plugin'` (the card then shows the tab). With this row + * disabled the capability reports 'unavailable' and the client keeps the + * tab hidden — no routes or state exist on this side either way. + */ +import type { CloudMemoryContext } from '../context-types.ts' +import { brainKernel } from '../kernel.ts' + +export const name = 'dsh-brain-mcp' + +/** Services required before `apply` runs (none: activation only). */ +export const inject: string[] = [] + +/** Register the sub-plugin with the host. */ +export function apply(ctx: CloudMemoryContext, config: unknown): void { + const kernel = brainKernel(config, ctx.logger('dsh-brain')) + kernel.activate('mcp') + ctx.effect(() => () => kernel.deactivate('mcp'), 'dsh-brain-mcp: activation') +} diff --git a/src/entries/memory.ts b/src/entries/memory.ts new file mode 100644 index 0000000..48afd9d --- /dev/null +++ b/src/entries/memory.ts @@ -0,0 +1,33 @@ +/** + * Memory sub-plugin entry — the five memory_* agent tools. + * + * Registers nothing but the tool set (no routes, no timers). It sees the + * cloud exclusively through the kernel's MemoryRemoteFactory, so it can be + * toggled independently of the cloud-sync entry that would otherwise own + * the connection. With this row disabled the agent loses memory_search / + * memory_add / … while the settings page, skill management, and activity + * reporting keep working. + */ +import type { CloudMemoryContext } from '../context-types.ts' +import { brainKernel } from '../kernel.ts' +import { createMemoryTools } from '../memory/tools.ts' + +export const name = 'dsh-brain-memory' + +/** Services required before `apply` runs. */ +export const inject = ['tools'] + +/** Register the sub-plugin with the host. */ +export function apply(ctx: CloudMemoryContext, config: unknown): void { + const kernel = brainKernel(config, ctx.logger('dsh-brain')) + kernel.activate('memory') + ctx.effect(() => () => kernel.deactivate('memory'), 'dsh-brain-memory: activation') + + ctx.inject(['tools'], (toolsCtx) => { + const tools = (toolsCtx as CloudMemoryContext).tools + if (tools === undefined) return + for (const tool of createMemoryTools(kernel.toolDeps())) { + toolsCtx.effect(() => tools.register(tool), `dsh-brain-memory: tool ${tool.name}`) + } + }) +} diff --git a/src/entries/settings-ui.ts b/src/entries/settings-ui.ts new file mode 100644 index 0000000..672997b --- /dev/null +++ b/src/entries/settings-ui.ts @@ -0,0 +1,39 @@ +/** + * Settings-UI sub-plugin entry — the configuration page and core routes. + * + * Owns the standalone HTML page, the status / capabilities / config / + * migrate routes, and their legacy /cloud-memory aliases. The capability + * report is assembled from the kernel's active-bundle view, so the page + * reflects which sibling sub-plugins are currently enabled. + */ +import type { CloudMemoryContext } from '../context-types.ts' +import { brainKernel, VERSION } from '../kernel.ts' +import { createCoreRoutes, legacyAliases } from '../routes.ts' +import { createSettingsUiRoutes } from '../settings-ui/routes.ts' + +export const name = 'dsh-brain-settings-ui' + +/** Services required before `apply` runs. */ +export const inject = ['webServer'] + +/** Register the sub-plugin with the host. */ +export function apply(ctx: CloudMemoryContext, config: unknown): void { + const logger = ctx.logger('dsh-brain') + const kernel = brainKernel(config, logger) + kernel.activate('settings-ui') + ctx.effect(() => () => kernel.deactivate('settings-ui'), 'dsh-brain-settings-ui: activation') + + const webServer = ctx.webServer + if (webServer === undefined) { + logger.warn('webServer service unavailable; the configuration page stays disabled') + return + } + const routes = [ + ...createSettingsUiRoutes({ version: VERSION, store: kernel.store }), + ...createCoreRoutes(kernel.routeDeps()), + ] + routes.push(...legacyAliases(routes)) + for (const route of routes) { + ctx.effect(() => webServer.register(route), `dsh-brain-settings-ui: route ${route.path}`) + } +} diff --git a/src/entries/skills.ts b/src/entries/skills.ts new file mode 100644 index 0000000..4993ada --- /dev/null +++ b/src/entries/skills.ts @@ -0,0 +1,53 @@ +/** + * Skill sub-plugin entry — local skill management. + * + * Owns the skill agent tools and the skills / market / clients routes (plus + * their legacy /cloud-memory aliases): inventory, install plans, market + * search, update/rollback, and the cross-software client registry. Sync + * itself belongs to the cloud-sync entry; the admin's write gate still + * consults the shared sync engine through the kernel. + */ +import type { CloudMemoryContext } from '../context-types.ts' +import { brainKernel, VERSION } from '../kernel.ts' +import { legacyAliases } from '../routes.ts' +import { createSkillRoutes } from '../skills/routes.ts' +import { createSkillTools } from '../tools.ts' + +export const name = 'dsh-brain-skills' + +/** Services required before `apply` runs. */ +export const inject = ['tools', 'webServer'] + +/** Register the sub-plugin with the host. */ +export function apply(ctx: CloudMemoryContext, config: unknown): void { + const logger = ctx.logger('dsh-brain') + const kernel = brainKernel(config, logger) + kernel.activate('skills') + ctx.effect(() => () => kernel.deactivate('skills'), 'dsh-brain-skills: activation') + + ctx.inject(['tools'], (toolsCtx) => { + const tools = (toolsCtx as CloudMemoryContext).tools + if (tools === undefined) return + for (const tool of createSkillTools(kernel.toolDeps())) { + toolsCtx.effect(() => tools.register(tool), `dsh-brain-skills: tool ${tool.name}`) + } + }) + + const webServer = ctx.webServer + if (webServer === undefined) { + logger.warn('webServer service unavailable; skill routes stay disabled') + return + } + const routes = createSkillRoutes({ + version: VERSION, + admin: kernel.skillAdmin, + groups: kernel.skillGroups, + market: kernel.market, + updates: kernel.updater, + clients: kernel.clients, + }) + routes.push(...legacyAliases(routes)) + for (const route of routes) { + ctx.effect(() => webServer.register(route), `dsh-brain-skills: route ${route.path}`) + } +} diff --git a/src/index.ts b/src/index.ts index 22f367f..4eb5abe 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,30 +1,22 @@ /** - * Plugin entry — host half. + * Plugin entry — compat root. * - * Responsibilities: - * 1. report one activity record per finished conversation round, - * 2. expose the memory tools to the agent, - * 3. serve the configuration page under `/dsh-brain` (legacy `/cloud-memory` routes stay as aliases). + * The package now ships five toggleable sub-plugin rows (see + * cordis.patch.yml): cloud-sync, memory, skills, mcp, and settings-ui. + * This root entry remains for older single-row profiles: it applies all + * five entries against the same context, so the route and tool tables it + * registers are identical to the pre-split build, including the legacy + * /cloud-memory aliases. * - * Everything registers through `ctx.effect(...)` so a plugin reload tears down - * its routes, timer, listeners, and tools without leftovers. + * Everything registers through `ctx.effect(...)` so a plugin reload tears + * down its routes, timers, listeners, and tools without leftovers. */ -import { CloudClient } from './api.ts' -import type { CloudMemoryContext, SessionEventLike, SessionLike } from './context-types.ts' -import { Reporter } from './reporter.ts' -import { createLegacyRoutes, createRoutes } from './routes.ts' -import { join, resolve } from 'node:path' -import { SettingsStore, dshHome } from './store.ts' -import { SkillSync } from './skill-sync.ts' -import { SkillAdmin, skillsHoldingDir } from './skill-admin.ts' -import { AdminSkillRepository } from './skills/repository.ts' -import { SkillGroupManager, detectSources } from './skill-groups.ts' -import { ClaudePluginMarketplaceProvider, MarketService } from './market.ts' -import { SkillUpdater } from './skill-update.ts' -import { ClientRegistry } from './clients.ts' -import { createCloudMemoryRemoteFactory } from './cloudsync.ts' -import { createMemoryTools } from './memory/tools.ts' -import { createSkillTools } from './tools.ts' +import type { CloudMemoryContext } from './context-types.ts' +import * as cloudsync from './entries/cloudsync.ts' +import * as memory from './entries/memory.ts' +import * as skills from './entries/skills.ts' +import * as mcp from './entries/mcp.ts' +import * as settingsUi from './entries/settings-ui.ts' /** Package name; also the client bundle id. */ export const name = 'dsh-brain' @@ -32,186 +24,11 @@ export const name = 'dsh-brain' /** Services required before `apply` runs. */ export const inject = ['webServer'] -/** Version reported by the status card. */ -const VERSION = '0.9.10' - -/** How often the skill directory is reconciled with the cloud center. */ -const SKILL_SYNC_INTERVAL_MS = 15 * 60_000 - -/** How often queued reports are retried. */ -const RETRY_INTERVAL_MS = 30_000 - -/** Register the plugin with the host. */ +/** Register the plugin with the host: all five sub-entries at once. */ export function apply(ctx: CloudMemoryContext, config: unknown): void { - const logger = ctx.logger('dsh-brain') - const store = new SettingsStore(config) - const settings = () => store.settings() - - // One client per instance; the settings closures keep it live across edits. - const client = new CloudClient({ - baseUrl: () => settings().baseUrl, - token: () => store.memoryToken(), - timeoutMs: () => settings().requestTimeoutMs, - }) - - // The memory bundle sees the cloud through this factory only: the concrete - // client stays a cloud-sync concern, injected here at the composition root. - const memoryRemoteFactory = createCloudMemoryRemoteFactory({ - settings: () => settings(), - memoryToken: () => store.memoryToken(), - }) - - const reporter = new Reporter({ - client, - settings: () => ({ enabled: settings().activityEnabled, clientId: settings().clientId }), - activityToken: () => store.activityToken(), - summary: () => ({ enabled: settings().summaryEnabled, maxChars: settings().summaryMaxChars }), - summaryToken: () => store.summaryToken(), - log: (message) => logger.warn(message), - }) - - // The skill bundle owns its folders; the composition root only wires the - // shared root path and the parking area. The sync engine touches folders - // exclusively through AdminSkillRepository below. - const skillsRootDir = (): string => { - const dir = settings().skillsDir - return dir !== '' ? resolve(dir) : join(dshHome(), 'skills') - } - - // Built before the sync engine: the gate closure below dereferences - // skillSync lazily, so the TDZ order here is safe. - const skillAdmin = new SkillAdmin({ - skillsRoot: skillsRootDir, - holdingDir: () => skillsHoldingDir(), - gate: () => skillSync, - log: (message) => logger.info(message), - }) - - // The skill bundle's public repository: the only door the cloud-sync - // engine has into skill folders. - const skillRepository = new AdminSkillRepository({ - admin: skillAdmin, - skillsRoot: skillsRootDir, - holdingDir: () => skillsHoldingDir(), - }) - - const skillSync: SkillSync = new SkillSync({ - client: () => client, - settings: () => ({ - enabled: settings().enabled, - skillsSyncEnabled: settings().skillsSyncEnabled, - }), - repository: () => skillRepository, - log: (message) => logger.info(message), - }) - - // The tree's sources are detected per call so a directory created while the - // process runs shows up on the next refresh. - const skillGroups = new SkillGroupManager({ - sources: () => detectSources(), - admin: skillAdmin, - log: (message) => logger.info(message), - }) - - // One verified market source to start with: the Claude Code plugin marketplace - // manifest that Anthropic publishes. Entry ids never carry a URL, so the card - // cannot make the host fetch an arbitrary repository. - const market = new MarketService([ - new ClaudePluginMarketplaceProvider({ - id: 'anthropic-skills', - label: 'Anthropic Agent Skills', - description: 'Anthropic 公开的 Claude 技能市场(.claude-plugin/marketplace.json)', - repo: 'anthropics/skills', - ref: 'main', - }), - ]) - - const updater = new SkillUpdater({ - admin: skillAdmin, - skillsRoot: skillsRootDir, - holdingDir: () => skillsHoldingDir(), - gate: () => skillSync, - log: (message) => logger.info(message), - }) - - // Cross-software / workspace inventory. Read-only for every client except DSH. - const clients = new ClientRegistry() - // Announce at most once per activation so a missing token is obvious in logs. - const effective = settings() - if (!effective.activityEnabled) { - logger.info('turn reporting disabled by settings') - } else if (store.activityToken() === '') { - logger.warn(`reporting enabled but no activity token; configure one at ${store.path} or open /dsh-brain`) - } else { - logger.info(`reporting to ${effective.baseUrl} as ${effective.clientId}`) - } - if (effective.summaryEnabled && store.summaryToken() === '') { - logger.info('turn summaries are enabled but no summary token is configured; nothing will be staged') - } - - // The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a - // third-party bundle cannot rely on; bind the listener through a local shape. - const onEvent = ctx.on as unknown as ( - name: 'session/event', - listener: (session: SessionLike, event: SessionEventLike) => void, - ) => () => void - - ctx.effect( - () => onEvent('session/event', (session, event) => { - try { - reporter.handleEvent(session, event) - } catch (error) { - logger.warn(`turn event handling failed: ${error instanceof Error ? error.message : String(error)}`) - } - }), - 'dsh-brain: turn reporting', - ) - - ctx.inject(['tools'], (toolsCtx) => { - const tools = (toolsCtx as CloudMemoryContext).tools - if (tools === undefined) return - const toolDeps = { - remote: () => memoryRemoteFactory.current(), - client: () => client, - memoryToken: () => store.memoryToken(), - settings: () => ({ enabled: settings().memoryEnabled, defaultK: settings().defaultK }), - } - for (const tool of [...createMemoryTools(toolDeps), ...createSkillTools(toolDeps)]) { - toolsCtx.effect(() => tools.register(tool), `dsh-brain: tool ${tool.name}`) - } - }) - - const webServer = ctx.webServer - if (webServer === undefined) { - logger.warn('webServer service unavailable; the configuration page stays disabled') - } else { - const routes = createRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin, groups: skillGroups, market, sync: skillSync, updates: updater, clients }) - routes.push(...createLegacyRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin, groups: skillGroups, market, sync: skillSync, updates: updater, clients })) - for (const route of routes) { - ctx.effect(() => webServer.register(route), `dsh-brain: route ${route.path}`) - } - } - - ctx.effect(() => { - const timer = setInterval(() => { - if (store.activityToken() !== '' && settings().activityEnabled) { - void reporter.flush().catch((error: unknown) => { - logger.warn(`retry flush failed: ${error instanceof Error ? error.message : String(error)}`) - }) - } - }, RETRY_INTERVAL_MS) - timer.unref?.() - return () => clearInterval(timer) - }, 'dsh-brain: retry timer') - - ctx.effect(() => { - const run = () => { - if (store.memoryToken() !== '') void skillSync.syncOnce().catch(() => {}) - } - const first = setTimeout(run, 5_000) - first.unref?.() - const timer = setInterval(run, SKILL_SYNC_INTERVAL_MS) - timer.unref?.() - return () => { clearTimeout(first); clearInterval(timer) } - }, 'dsh-brain: skill sync timer') + cloudsync.apply(ctx, config) + memory.apply(ctx, config) + skills.apply(ctx, config) + mcp.apply(ctx, config) + settingsUi.apply(ctx, config) } diff --git a/src/kernel.ts b/src/kernel.ts new file mode 100644 index 0000000..0dfe172 --- /dev/null +++ b/src/kernel.ts @@ -0,0 +1,245 @@ +/** + * Shared kernel for the dsh-brain sub-plugins. + * + * The five bundle entries (dsh-brain/cloudsync, dsh-brain/memory, + * dsh-brain/skills, dsh-brain/mcp, dsh-brain/settings-ui) and the compat + * root entry all load from the same package inside the same host process, + * so this module's export resolves to a single instance: whichever entry + * applies first builds the services, the rest reuse them. + * + * The kernel holds service OBJECTS only. Routes, tools, timers, and the + * session listener belong to the entry that registers them through its own + * `ctx.effect(...)`, so toggling a sub-plugin off in the host plugin + * settings tears down exactly that slice and nothing else. `routeDeps()` + * assembles the RouteDeps view from the currently active bundles, which is + * how `/status` and `/capabilities` report what is actually enabled. + * + * Settings persist in `$DSH_HOME/dsh-brain.json`; the row config each + * entry receives is only the first-boot seed, so any entry may seed the + * kernel without diverging. + */ +import { join, resolve } from 'node:path' +import { CloudClient } from './api.ts' +import { createCloudMemoryRemoteFactory } from './cloudsync.ts' +import { ClientRegistry } from './clients.ts' +import { ClaudePluginMarketplaceProvider, MarketService } from './market.ts' +import { Reporter } from './reporter.ts' +import type { RouteDeps } from './routes.ts' +import { SkillAdmin, skillsHoldingDir } from './skill-admin.ts' +import { SkillGroupManager, detectSources } from './skill-groups.ts' +import { SkillSync } from './skill-sync.ts' +import { SkillUpdater } from './skill-update.ts' +import { SettingsStore, dshHome } from './store.ts' +import { AdminSkillRepository } from './skills/repository.ts' + +/** Version reported by the status card. */ +export const VERSION = '0.9.11' + +/** Logger face the kernel services need (the first entry supplies the host one). */ +export interface KernelLogger { + info: (message: string) => void + warn: (message: string) => void +} + +/** The bundles a sub-plugin entry can activate. */ +export type BrainBundle = 'cloudsync' | 'memory' | 'skills' | 'mcp' | 'settings-ui' + +/** The shared service set behind every dsh-brain sub-plugin entry. */ +export class BrainKernel { + private readonly active = new Set() + private readonly settingsOf: () => ReturnType + + readonly store: SettingsStore + readonly client: CloudClient + readonly memoryRemoteFactory: ReturnType + readonly reporter: Reporter + readonly skillAdmin: SkillAdmin + readonly skillRepository: AdminSkillRepository + readonly skillSync: SkillSync + readonly skillGroups: SkillGroupManager + readonly market: MarketService + readonly updater: SkillUpdater + readonly clients: ClientRegistry + + constructor(config: unknown, logger: KernelLogger) { + const store = new SettingsStore(config) + this.store = store + const settings = () => store.settings() + this.settingsOf = settings + + // One client per instance; the settings closures keep it live across edits. + const client = new CloudClient({ + baseUrl: () => settings().baseUrl, + token: () => store.memoryToken(), + timeoutMs: () => settings().requestTimeoutMs, + }) + this.client = client + + // The memory bundle sees the cloud through this factory only: the concrete + // client stays a cloud-sync concern, injected here at the composition root. + this.memoryRemoteFactory = createCloudMemoryRemoteFactory({ + settings: () => settings(), + memoryToken: () => store.memoryToken(), + }) + + this.reporter = new Reporter({ + client, + settings: () => ({ enabled: settings().activityEnabled, clientId: settings().clientId }), + activityToken: () => store.activityToken(), + summary: () => ({ enabled: settings().summaryEnabled, maxChars: settings().summaryMaxChars }), + summaryToken: () => store.summaryToken(), + log: (message) => logger.warn(message), + }) + + // The skill bundle owns its folders; the kernel only wires the shared root + // path and the parking area. The sync engine touches folders exclusively + // through AdminSkillRepository below. + const skillsRootDir = (): string => { + const dir = settings().skillsDir + return dir !== '' ? resolve(dir) : join(dshHome(), 'skills') + } + + // Built before the sync engine: the gate closures dereference skillSync + // lazily, so the TDZ order here is safe. + const skillAdmin = new SkillAdmin({ + skillsRoot: skillsRootDir, + holdingDir: () => skillsHoldingDir(), + gate: () => this.skillSync, + log: (message) => logger.info(message), + }) + this.skillAdmin = skillAdmin + + this.skillRepository = new AdminSkillRepository({ + admin: skillAdmin, + skillsRoot: skillsRootDir, + holdingDir: () => skillsHoldingDir(), + }) + + this.skillSync = new SkillSync({ + client: () => client, + settings: () => ({ + enabled: settings().enabled, + skillsSyncEnabled: settings().skillsSyncEnabled, + }), + repository: () => this.skillRepository, + log: (message) => logger.info(message), + }) + + // The tree's sources are detected per call so a directory created while + // the process runs shows up on the next refresh. + this.skillGroups = new SkillGroupManager({ + sources: () => detectSources(), + admin: skillAdmin, + log: (message) => logger.info(message), + }) + + // One verified market source to start with: the Claude Code plugin + // marketplace manifest that Anthropic publishes. Entry ids never carry a + // URL, so the card cannot make the host fetch an arbitrary repository. + this.market = new MarketService([ + new ClaudePluginMarketplaceProvider({ + id: 'anthropic-skills', + label: 'Anthropic Agent Skills', + description: 'Anthropic 公开的 Claude 技能市场(.claude-plugin/marketplace.json)', + repo: 'anthropics/skills', + ref: 'main', + }), + ]) + + this.updater = new SkillUpdater({ + admin: skillAdmin, + skillsRoot: skillsRootDir, + holdingDir: () => skillsHoldingDir(), + gate: () => this.skillSync, + log: (message) => logger.info(message), + }) + + // Cross-software / workspace inventory. Read-only for every client but DSH. + this.clients = new ClientRegistry() + + // Announce at most once per kernel so a missing token is obvious in logs. + const effective = settings() + if (!effective.activityEnabled) { + logger.info('turn reporting disabled by settings') + } else if (store.activityToken() === '') { + logger.warn(`reporting enabled but no activity token; configure one at ${store.path} or open /dsh-brain`) + } else { + logger.info(`reporting to ${effective.baseUrl} as ${effective.clientId}`) + } + if (effective.summaryEnabled && store.summaryToken() === '') { + logger.info('turn summaries are enabled but no summary token is configured; nothing will be staged') + } + } + + /** Current settings snapshot (live: re-read on every call). */ + settings(): ReturnType { + return this.settingsOf() + } + + /** Mark a bundle's entry as applied; feeds `routeDeps()` gating. */ + activate(bundle: BrainBundle): void { + this.active.add(bundle) + } + + /** Drop a bundle from the active set (entry teardown). */ + deactivate(bundle: BrainBundle): void { + this.active.delete(bundle) + } + + /** Whether a bundle's entry is currently applied. */ + isActive(bundle: BrainBundle): boolean { + return this.active.has(bundle) + } + + /** Tool deps shared by the memory and skill entries. */ + toolDeps() { + const store = this.store + const settings = this.settingsOf + return { + remote: () => this.memoryRemoteFactory.current(), + client: () => this.client, + memoryToken: () => store.memoryToken(), + settings: () => ({ enabled: settings().memoryEnabled, defaultK: settings().defaultK }), + } + } + + /** + * RouteDeps assembled from the currently active bundles: the status card + * then reports exactly what is on, not what this build could do. + */ + routeDeps(): RouteDeps { + const skills = this.isActive('skills') + const cloudsync = this.isActive('cloudsync') + return { + version: VERSION, + store: this.store, + reporter: this.reporter, + client: () => this.client, + skills: cloudsync ? () => this.skillSync.stats() : undefined, + admin: skills ? this.skillAdmin : undefined, + groups: skills ? this.skillGroups : undefined, + market: skills ? this.market : undefined, + sync: cloudsync ? this.skillSync : undefined, + updates: skills ? this.updater : undefined, + clients: skills ? this.clients : undefined, + mcp: this.isActive('mcp'), + } + } +} + +let instance: BrainKernel | undefined + +/** + * The process-wide kernel. The first entry to apply builds it (seeding from + * that row's config; the sidecar file is authoritative afterwards); every + * later entry — and the compat root — reuses the same instance. + */ +export function brainKernel(config: unknown, logger: KernelLogger): BrainKernel { + if (instance === undefined) instance = new BrainKernel(config, logger) + return instance +} + +/** Test hook: drop the singleton so the next call rebuilds it. */ +export function resetBrainKernel(): void { + instance = undefined +} diff --git a/src/routes.ts b/src/routes.ts index db6581e..21361a6 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -32,7 +32,7 @@ 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 } from './mcp.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' @@ -73,6 +73,8 @@ export interface RouteDeps { 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 } /** One feature flag the card reads before it renders a control. */ @@ -101,10 +103,16 @@ export interface CapabilityReport { 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 = mcpCapability() + const mcp = deps.mcp === true ? mcpCapability() : MCP_UNAVAILABLE return { version: deps.version, features: { @@ -137,7 +145,7 @@ function capabilities(deps: RouteDeps): CapabilityReport { } /** The payload the page and the client card both consume. */ -function statusPayload(deps: RouteDeps): Record { +export function buildStatusPayload(deps: RouteDeps): Record { const view: SettingsView = deps.store.describe() const tokens = { activity: view.activityToken as TokenView, @@ -178,7 +186,7 @@ function serveStatus(deps: RouteDeps, req: IncomingMessage, res: ServerResponse) fail(res, 405, 'method-not-allowed') return } - json(res, 200, statusPayload(deps)) + json(res, 200, buildStatusPayload(deps)) } /** `GET /dsh-brain/capabilities`. */ @@ -222,7 +230,7 @@ async function serveConfig(deps: RouteDeps, req: IncomingMessage, res: ServerRes return } json(res, 200, { - ...statusPayload(deps), + ...buildStatusPayload(deps), ...(result.clearedTokens === undefined ? {} : { credentialsCleared: result.clearedTokens }), }) } @@ -240,9 +248,18 @@ async function serveMigrate(_deps: RouteDeps, req: IncomingMessage, res: ServerR fail(res, 404, 'unknown-migrate-route') } -/** Pre-rename aliases (0.8.0): the same handlers under the old `/cloud-memory` prefix. */ +/** + * 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 createRoutes(deps).map((route) => ({ ...route, path: route.path.replace('/dsh-brain', '/cloud-memory') })) + return legacyAliases(createRoutes(deps)) } /** @@ -256,6 +273,32 @@ export function createLegacyRoutes(deps: RouteDeps): CloudMemoryWebRoute[] { 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: 'exact', path: ROUTES.status, @@ -271,21 +314,6 @@ export function createRoutes(deps: RouteDeps): CloudMemoryWebRoute[] { 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, diff --git a/verify-plugin-entry.mjs b/verify-plugin-entry.mjs index 5235267..3872598 100644 --- a/verify-plugin-entry.mjs +++ b/verify-plugin-entry.mjs @@ -1,9 +1,11 @@ -// Entry-point smoke test: a plugin that throws from `apply` takes the whole web -// boot down, so the cheapest insurance is to activate the real entry against a -// fake host context and check the route table it registers. +// Entry-point smoke test: a plugin that throws from `apply` takes the whole +// web boot down, so the cheapest insurance is to activate the real entries +// against a fake host context and check the route/tool tables they register. // -// Deliberately not a unit test of every timer: it proves `apply` runs, wires the -// expected routes, and tears everything down through the disposers it returned. +// Deliberately not a unit test of every timer: it proves `apply` runs, wires +// the expected routes, tears down through the disposers it returned, and — +// since the five-row split — that each sub-plugin entry registers exactly its +// own slice and that /status reflects which siblings are enabled. import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -16,49 +18,159 @@ function check(name, ok, detail) { console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`) } -const { apply } = await import('./lib/index.js') +const noop = () => {} +const quietLogger = { info: noop, warn: noop } -const routes = [] -const disposers = [] -const tools = [] -const ctx = { - logger: () => ({ info: () => {}, warn: () => {} }), - effect: (fn) => { - const result = fn() - if (typeof result === 'function') disposers.push(result) - return () => {} - }, - on: () => () => {}, - inject: (deps, fn) => { - fn({ - tools: { - register: (tool) => { - tools.push(tool) +/** A fresh host-shaped context recording its own routes and tools. */ +function fakeCtx() { + const routes = [] + const tools = [] + const disposers = [] + return { + routes, + tools, + disposers, + ctx: { + logger: () => quietLogger, + effect: (fn) => { + const result = fn() + if (typeof result === 'function') disposers.push(result) + return () => {} + }, + on: () => () => {}, + inject: (deps, fn) => { + fn({ + tools: { + register: (tool) => { + tools.push(tool) + return () => {} + }, + }, + effect: (inner) => { + inner() + return () => {} + }, + }) + }, + webServer: { + register: (route) => { + routes.push(route) return () => {} }, }, - effect: (inner) => { - inner() - return () => {} - }, - }) - }, - webServer: { - register: (route) => { - routes.push(route) - return () => {} }, - }, + } } +const { resetBrainKernel, brainKernel } = await import('./lib/kernel.js') +const cloudsyncEntry = await import('./lib/entries/cloudsync.js') +const memoryEntry = await import('./lib/entries/memory.js') +const skillsEntry = await import('./lib/entries/skills.js') +const mcpEntry = await import('./lib/entries/mcp.js') +const settingsUiEntry = await import('./lib/entries/settings-ui.js') +const { buildStatusPayload } = await import('./lib/routes.js') +const root = await import('./lib/index.js') + +const SEED = { baseUrl: 'https://your-memory-host/api/longmemory', clientId: 'smoke' } + +// --- per-entry slice checks ------------------------------------------------- +resetBrainKernel() + +let ui = fakeCtx() +settingsUiEntry.apply(ui.ctx, SEED) +const uiPaths = ui.routes.map((route) => `${route.kind}:${route.path}`) +check('settings-ui entry applies and registers the page + core routes', [ + 'exact:/dsh-brain', + 'exact:/dsh-brain/status', + 'exact:/dsh-brain/capabilities', + 'exact:/dsh-brain/config', + 'prefix:/dsh-brain/migrate', + 'exact:/cloud-memory', + 'exact:/cloud-memory/status', + 'exact:/cloud-memory/capabilities', + 'exact:/cloud-memory/config', + 'prefix:/cloud-memory/migrate', +].every((item) => uiPaths.includes(item)), uiPaths.join(' | ')) +check('settings-ui entry registers no tools', ui.tools.length === 0, `${ui.tools.length} tools`) + +const mcpCtx = fakeCtx() +mcpEntry.apply(mcpCtx.ctx, SEED) +check('mcp entry applies and registers no routes and no tools', + mcpCtx.routes.length === 0 && mcpCtx.tools.length === 0, + `${mcpCtx.routes.length} routes, ${mcpCtx.tools.length} tools`) + +const sync = fakeCtx() +cloudsyncEntry.apply(sync.ctx, SEED) +const syncPaths = sync.routes.map((route) => `${route.kind}:${route.path}`) +check('cloudsync entry applies and registers login/test/flush/sync routes', [ + 'exact:/dsh-brain/login', + 'exact:/dsh-brain/test', + 'exact:/dsh-brain/flush', + 'prefix:/dsh-brain/sync', + 'exact:/cloud-memory/login', + 'exact:/cloud-memory/test', + 'exact:/cloud-memory/flush', + 'prefix:/cloud-memory/sync', +].every((item) => syncPaths.includes(item)), syncPaths.join(' | ')) +check('cloudsync entry registers no tools', sync.tools.length === 0, `${sync.tools.length} tools`) + +const mem = fakeCtx() +memoryEntry.apply(mem.ctx, SEED) +check('memory entry applies and registers the memory tools', mem.tools.length >= 5, `${mem.tools.length} tools`) +check('memory entry registers no routes', mem.routes.length === 0, `${mem.routes.length} routes`) + +const skill = fakeCtx() +skillsEntry.apply(skill.ctx, SEED) +const skillPaths = skill.routes.map((route) => `${route.kind}:${route.path}`) +check('skills entry applies and registers skills/market/clients routes', [ + 'prefix:/dsh-brain/skills', + 'prefix:/dsh-brain/market', + 'prefix:/dsh-brain/clients', + 'prefix:/cloud-memory/skills', + 'prefix:/cloud-memory/market', + 'prefix:/cloud-memory/clients', +].every((item) => skillPaths.includes(item)), skillPaths.join(' | ')) +check('skills entry registers the skill tools', skill.tools.length >= 1, `${skill.tools.length} tools`) + +// --- active-bundle gating --------------------------------------------------- +const kernel = brainKernel(SEED, quietLogger) +const withAll = buildStatusPayload(kernel.routeDeps()) +check('status reports skills and sync with all five entries applied', + withAll.capabilities.features.skills === true + && withAll.capabilities.features.skillsSync === true + && withAll.capabilities.features.mcpBridge === 'host-plugin', + JSON.stringify(withAll.capabilities.features)) + +kernel.deactivate('skills') +const withoutSkills = buildStatusPayload(kernel.routeDeps()) +check('deactivating the skills entry turns the skill capabilities off', + withoutSkills.capabilities.features.skills === false + && withoutSkills.capabilities.features.skillInstallPlans === false + && withoutSkills.capabilities.features.skillUpdate === false + && withoutSkills.capabilities.features.multiClient === false, + JSON.stringify(withoutSkills.capabilities.features)) + +kernel.deactivate('mcp') +kernel.deactivate('cloudsync') +const withoutMcpOrSync = buildStatusPayload(kernel.routeDeps()) +check('deactivating mcp and cloudsync gates the tab and sync flags', + withoutMcpOrSync.capabilities.features.mcpBridge === 'unavailable' + && withoutMcpOrSync.capabilities.features.skillsSync === false + && withoutMcpOrSync.capabilities.features.syncResolve === false, + JSON.stringify(withoutMcpOrSync.capabilities.features)) + +// --- compat root ------------------------------------------------------------- +resetBrainKernel() +const rootHost = fakeCtx() + let applied = true try { - apply(ctx, { baseUrl: 'https://your-memory-host/api/longmemory', clientId: 'smoke' }) + root.apply(rootHost.ctx, SEED) } catch (failure) { applied = false console.log('apply threw:', failure) } -check('apply() completes against a host-shaped context', applied) +check('compat root apply() completes against a host-shaped context', applied) const expected = [ 'exact:/cloud-memory', @@ -74,19 +186,14 @@ const expected = [ 'prefix:/cloud-memory/clients', 'prefix:/cloud-memory/migrate', ] -const actual = routes.map((route) => `${route.kind}:${route.path}`) -check('every route the card depends on is registered', expected.every((item) => actual.includes(item)), actual.join(' | ')) -check('the memory tools are still registered', tools.length >= 3, `${tools.length} tools`) +const rootPaths = rootHost.routes.map((route) => `${route.kind}:${route.path}`) +check('root registers every route the card depends on (legacy aliases included)', + expected.every((item) => rootPaths.includes(item)), rootPaths.join(' | ')) +check('root registers the modern /dsh-brain route table', + ['exact:/dsh-brain', 'exact:/dsh-brain/status', 'prefix:/dsh-brain/skills', 'prefix:/dsh-brain/sync'] + .every((item) => rootPaths.includes(item))) +check('the memory tools are still registered', rootHost.tools.length >= 3, `${rootHost.tools.length} tools`) -let disposed = true -try { - for (const dispose of disposers) dispose() -} catch (failure) { - disposed = false - console.log('dispose threw:', failure) -} -check('every registered effect is disposable', disposed) - -const failed = results.filter((item) => !item.ok).length -console.log(failed === 0 ? `\nALL ${results.length} CHECKS PASSED` : `\n${failed} CHECK(S) FAILED`) -process.exit(failed === 0 ? 0 : 1) +const failed = results.filter((item) => !item.ok) +console.log(failed.length === 0 ? 'ALL PASS' : `${failed.length} FAILURE(S)`) +process.exitCode = failed.length === 0 ? 0 : 1