137 lines
6.3 KiB
JavaScript
137 lines
6.3 KiB
JavaScript
import { brainKernel } from "../kernel.js";
|
|
import { createMemoryTools } from "../memory/tools.js";
|
|
import { createDepartmentTools } from "../memory/departments-tools.js";
|
|
import { conversationIdOf, redactSecrets, textOf, turnOf } from "../reporter.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 logger = ctx.logger('dsh-brain');
|
|
const kernel = brainKernel(config, logger);
|
|
kernel.activate('memory');
|
|
kernel.logEvent('boot.entry', { bundle: '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}`);
|
|
}
|
|
for (const tool of createDepartmentTools(kernel.departmentToolDeps())) {
|
|
toolsCtx.effect(() => tools.register(tool), `dsh-brain-memory: tool ${tool.name}`);
|
|
}
|
|
});
|
|
// Project the compact USER.md/MEMORY.md state into the system prompt each turn.
|
|
// The files are generated from explicit profile/rule records only.
|
|
ctx.inject(['systemPrompt'], (prompted) => {
|
|
const host = prompted;
|
|
const service = typeof host.get === 'function' ? host.get('systemPrompt') : host.systemPrompt;
|
|
const prompt = service;
|
|
prompt?.section?.({
|
|
name: 'dsh-brain:local-memory',
|
|
order: 151,
|
|
text: () => kernel.settings().localMemoryEnabled === false ? '' : kernel.localMemory.projectionText(),
|
|
});
|
|
});
|
|
// Local automatic summary: consume real host messages (structured content),
|
|
// ignore host/plugin injections, and persist progress by stable session + turn.
|
|
const turns = new Map();
|
|
const pending = new Map();
|
|
const openTurns = new Map();
|
|
let flushing = false;
|
|
let retryTimer;
|
|
const onEvent = ctx.on;
|
|
const workspaceOfSession = (session) => session.cwd ?? session.workspace ?? session.header?.cwd ?? session.header?.workspace;
|
|
const isInjected = (value) => {
|
|
if (value === null || typeof value !== 'object')
|
|
return false;
|
|
const source = value.source;
|
|
if (source === null || typeof source !== 'object')
|
|
return false;
|
|
const kind = source.kind;
|
|
return typeof kind === 'string' && kind !== 'user';
|
|
};
|
|
const flushPending = async () => {
|
|
if (flushing || pending.size === 0)
|
|
return;
|
|
flushing = true;
|
|
try {
|
|
for (const [key, item] of [...pending]) {
|
|
try {
|
|
await kernel.localMemory.withWorkspace(item.workspace, () => kernel.localMemory.summarizeConversation({
|
|
sessionId: item.conversation,
|
|
turns: [{ turnId: String(item.turn), user: item.user }],
|
|
}, item.workspace));
|
|
pending.delete(key);
|
|
}
|
|
catch (error) {
|
|
item.attempts += 1;
|
|
logger.warn('dsh-brain local summary failed (will retry): ' + (error instanceof Error ? error.message : String(error)));
|
|
}
|
|
}
|
|
}
|
|
finally {
|
|
flushing = false;
|
|
if (pending.size > 0) {
|
|
if (retryTimer !== undefined)
|
|
clearTimeout(retryTimer);
|
|
retryTimer = setTimeout(() => { retryTimer = undefined; void flushPending(); }, 2000);
|
|
retryTimer.unref?.();
|
|
}
|
|
}
|
|
};
|
|
ctx.effect(() => {
|
|
const dispose = onEvent('session/event', (session, event) => {
|
|
const conversation = conversationIdOf(session);
|
|
if (conversation === undefined)
|
|
return;
|
|
if (event.type === 'turn/start') {
|
|
const started = turnOf(event.data);
|
|
if (started !== undefined)
|
|
openTurns.set(conversation, started);
|
|
void flushPending();
|
|
return;
|
|
}
|
|
const eventTurn = turnOf(event.data);
|
|
const turn = eventTurn ?? openTurns.get(conversation);
|
|
if (event.type === 'user/message') {
|
|
const raw = textOf(event.data?.message ?? event.data);
|
|
if (turn === undefined || raw === undefined || isInjected(event.data?.message ?? event.data))
|
|
return;
|
|
const key = conversation + ':' + String(turn);
|
|
const entry = turns.get(key) ?? { turn, user: [] };
|
|
entry.user.push(redactSecrets(raw).slice(0, 4000));
|
|
turns.set(key, entry);
|
|
return;
|
|
}
|
|
if (event.type === 'turn/end' && turn !== undefined) {
|
|
const key = conversation + ':' + String(turn);
|
|
const entry = turns.get(key);
|
|
turns.delete(key);
|
|
if (eventTurn === undefined || openTurns.get(conversation) === eventTurn)
|
|
openTurns.delete(conversation);
|
|
if (entry === undefined || entry.user.length === 0)
|
|
return;
|
|
const settings = kernel.settings();
|
|
if (settings.localMemoryEnabled === false || settings.autoSummaryEnabled === false)
|
|
return;
|
|
pending.set(key, { conversation, turn, ...(workspaceOfSession(session) === undefined ? {} : { workspace: workspaceOfSession(session) }), user: entry.user.join('\n'), attempts: 0 });
|
|
void flushPending();
|
|
return;
|
|
}
|
|
if (event.type === 'session/end' || event.type === 'session/close' || event.type === 'session/closed' || event.type === 'session/terminated') {
|
|
openTurns.delete(conversation);
|
|
for (const key of turns.keys())
|
|
if (key.startsWith(conversation + ':'))
|
|
turns.delete(key);
|
|
}
|
|
});
|
|
return () => { dispose(); if (retryTimer !== undefined) {
|
|
clearTimeout(retryTimer);
|
|
retryTimer = undefined;
|
|
} };
|
|
}, 'dsh-brain-memory: local summary');
|
|
}
|