/** * 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; }