/** * 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 { DepartmentManager, LocalMemoryManager, LocalMemoryRemote } from './local-memory/index.ts' import { VERSION } from './version.ts' import { createCloudMemoryRemoteFactory } from './cloudsync.ts' import type { DepartmentToolDeps } from './memory/departments-tools.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 (single source: package.json). */ export { VERSION } /** 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. */ /** Resolve a workspace from the different host tool/session context shapes. */ function workspaceFromExec(exec: unknown): string | undefined { if (exec === null || typeof exec !== 'object') return undefined const value = exec as Record const candidates = [ value.workspace, value.cwd, value.projectPath, value.session?.cwd, value.session?.workspace, value.session?.header?.cwd, value.session?.header?.workspace, value.agent?.session?.cwd, value.agent?.session?.header?.cwd, ] for (const candidate of candidates) { if (typeof candidate === 'string' && candidate.trim() !== '') return candidate } return undefined } export class BrainKernel { private readonly active = new Set() private readonly settingsOf: () => ReturnType readonly store: SettingsStore readonly client: CloudClient readonly memoryRemoteFactory: ReturnType readonly localMemory: LocalMemoryManager readonly localMemoryRemote: LocalMemoryRemote readonly departments: DepartmentManager 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(), }) // Local-first memory is independent of the cloud adapter: it initializes // lazily on the first memory tool call and needs no token or account. this.localMemory = new LocalMemoryManager({ cwd: () => process.cwd(), settings: () => ({ localMemoryEnabled: settings().localMemoryEnabled, cloudMemoryEnabled: settings().cloudMemoryEnabled, autoMemorySpaces: settings().autoMemorySpaces, autoSummaryEnabled: settings().autoSummaryEnabled, autoProfileEnabled: settings().autoProfileEnabled, localMemoryK: settings().localMemoryK, }), }) this.localMemoryRemote = new LocalMemoryRemote(this.localMemory) this.departments = new DepartmentManager({ memory: this.localMemory }) // The global space is part of first boot; project space stays lazy until // the first memory use in that project. if (settings().localMemoryEnabled !== false && settings().autoMemorySpaces !== false) void this.localMemory.ensureGlobal().catch((error: unknown) => { logger.warn('dsh-brain local memory initialization failed: ' + (error instanceof Error ? error.message : String(error))) }) this.reporter = new Reporter({ // Pinned clients: one request leaves under the connection it started // with, never under whatever settings say by the time it lands. clientFor: (context) => new CloudClient({ baseUrl: () => context.baseUrl, token: () => context.activityToken, timeoutMs: () => context.timeoutMs, }), settings: () => ({ enabled: settings().activityEnabled, clientId: settings().clientId }), activityToken: () => store.activityToken(), baseUrl: () => settings().baseUrl, summary: () => ({ enabled: settings().summaryEnabled, maxChars: settings().summaryMaxChars }), summaryToken: () => store.summaryToken(), timeoutMs: () => settings().requestTimeoutMs, 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, clientForScope: (scope) => new CloudClient({ baseUrl: () => scope.endpoint, token: () => scope.accountToken, timeoutMs: () => settings().requestTimeoutMs, }), settings: () => ({ enabled: settings().enabled, skillsSyncEnabled: settings().skillsSyncEnabled, }), repository: () => this.skillRepository, repositoryForScope: (scope) => new AdminSkillRepository({ admin: skillAdmin, skillsRoot: () => scope.root, holdingDir: () => skillsHoldingDir(), }), scope: () => ({ endpoint: settings().baseUrl, accountToken: store.memoryToken(), root: skillsRootDir(), }), 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. */ departmentToolDeps(): DepartmentToolDeps { return { departments: () => this.departments, settings: () => ({ localMemoryEnabled: this.settingsOf().localMemoryEnabled, memoryEnabled: this.settingsOf().memoryEnabled }), workspace: (exec?: unknown) => workspaceFromExec(exec), } } toolDeps() { const store = this.store const settings = this.settingsOf return { // Local-first by default. The cloud adapter is only selected when the // user explicitly enables it AND has a memory token; otherwise memory // tools stay fully usable offline. remote: () => { const effective = settings() const localEnabled = effective.localMemoryEnabled !== false const cloudEnabled = effective.cloudMemoryEnabled === true && store.memoryToken() !== '' if (cloudEnabled) return this.memoryRemoteFactory.current() if (localEnabled) return this.localMemoryRemote throw new Error('memory_disabled') }, client: () => this.client, memoryToken: () => store.memoryToken(), settings: () => { const effective = settings() const local = effective.localMemoryEnabled !== false && !(effective.cloudMemoryEnabled === true && store.memoryToken() !== '') return { enabled: effective.memoryEnabled, defaultK: local ? effective.localMemoryK : effective.defaultK } }, localMemory: () => settings().localMemoryEnabled !== false, workspace: (exec?: unknown) => workspaceFromExec(exec), } } /** * 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'), localMemory: this.localMemory, departments: this.departments, } } } 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 }