297 lines
13 KiB
JavaScript
297 lines
13 KiB
JavaScript
/**
|
||
* 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 { DepartmentManager, LocalMemoryManager, LocalMemoryRemote } from "./local-memory/index.js";
|
||
import { VERSION } from "./version.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 (single source: package.json). */
|
||
export { VERSION };
|
||
/** 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) {
|
||
if (exec === null || typeof exec !== 'object')
|
||
return undefined;
|
||
const value = exec;
|
||
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 {
|
||
active = new Set();
|
||
settingsOf;
|
||
store;
|
||
client;
|
||
memoryRemoteFactory;
|
||
localMemory;
|
||
localMemoryRemote;
|
||
departments;
|
||
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(),
|
||
});
|
||
// 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) => { 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 = () => {
|
||
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() {
|
||
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 {
|
||
// 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) => 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() {
|
||
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;
|
||
/**
|
||
* 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;
|
||
}
|