dsh-brain/src/entries/memory.ts

139 lines
6.5 KiB
TypeScript

/**
* 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, SessionEventLike, SessionLike } from '../context-types.ts'
import { brainKernel } from '../kernel.ts'
import { createMemoryTools } from '../memory/tools.ts'
import { createDepartmentTools } from '../memory/departments-tools.ts'
import { conversationIdOf, redactSecrets, textOf, turnOf } from '../reporter.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 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 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}`)
}
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 as unknown as { get?: (name: string) => unknown; systemPrompt?: unknown }
const service = typeof host.get === 'function' ? host.get('systemPrompt') : host.systemPrompt
const prompt = service as { section?: (value: { name: string; order: number; text: () => string }) => unknown } | undefined
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<string, { turn: number; user: string[] }>()
const pending = new Map<string, { conversation: string; turn: number; workspace?: string; user: string; attempts: number }>()
const openTurns = new Map<string, number>()
let flushing = false
let retryTimer: ReturnType<typeof setTimeout> | undefined
const onEvent = ctx.on as unknown as (
name: 'session/event',
listener: (session: SessionLike, event: SessionEventLike) => void,
) => () => void
const workspaceOfSession = (session: SessionLike): string | undefined =>
session.cwd ?? session.workspace ?? session.header?.cwd ?? session.header?.workspace
const isInjected = (value: unknown): boolean => {
if (value === null || typeof value !== 'object') return false
const source = (value as Record<string, unknown>).source
if (source === null || typeof source !== 'object') return false
const kind = (source as Record<string, unknown>).kind
return typeof kind === 'string' && kind !== 'user'
}
const flushPending = async (): Promise<void> => {
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')
}