@tangjs/dsh-memory 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/icon.svg ADDED
@@ -0,0 +1,8 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Memory notes">
2
+ <rect width="64" height="64" rx="14" fill="#F7F1EA"/>
3
+ <path d="M20 16h20l8 8v24a2 2 0 0 1-2 2H20a2 2 0 0 1-2-2V18a2 2 0 0 1 2-2z" fill="#FFFFFF" stroke="#D77757" stroke-width="3" stroke-linejoin="round"/>
4
+ <path d="M40 16v8h8" fill="none" stroke="#D77757" stroke-width="3" stroke-linejoin="round"/>
5
+ <path d="M25 34h15M25 41h10" stroke="#5769F7" stroke-width="3" stroke-linecap="round"/>
6
+ <circle cx="45" cy="45" r="7" fill="#D77757"/>
7
+ <path d="M45 41v8M41 45h8" stroke="#FFFFFF" stroke-width="2.5" stroke-linecap="round"/>
8
+ </svg>
package/index.js ADDED
@@ -0,0 +1,582 @@
1
+ // dsh-memory — hierarchical, workspace-scoped memory notes for DeepSeek Harness.
2
+ //
3
+ // Host assembly only: every piece of logic lives in src/host/*.mjs, which import
4
+ // nothing from @deepseek-ai/* so CI can test them without the harness. This file
5
+ // is the single place that touches harness services.
6
+
7
+ import { join } from 'node:path'
8
+ import Schema from '@deepseek-ai/schemastery'
9
+ import { defineTool } from '@deepseek-ai/dsh-tools'
10
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
11
+ import { createApiHandler, API_PREFIX } from './src/host/api.mjs'
12
+ import { buildDreamPrompt, collectDreamHints, summarizeDreamApply } from './src/host/dream.mjs'
13
+ import { normalizeConfig, resolveStorageRoot } from './src/host/config.mjs'
14
+ import { AUTO_DREAM_STATE_FILE, createAutoDream } from './src/host/autoDream.mjs'
15
+ import { createDreamAgentRunner, validateDreamAgentPlan } from './src/host/dreamAgent.mjs'
16
+ import { createExtractor } from './src/host/extract.mjs'
17
+ import { buildMemorySection, SECTION_ORDER } from './src/host/prompt.mjs'
18
+ import { buildIndexInjection } from './src/host/memoryIndex.mjs'
19
+ import { createRecall, formatRecall } from './src/host/recall.mjs'
20
+ import { rankNotes } from './src/host/score.mjs'
21
+ import { GLOBAL_SPACE, spaceKeyFor, createStore } from './src/host/store.mjs'
22
+ import { createHandlers } from './src/host/tool.mjs'
23
+
24
+ export const inject = ['tools', 'systemPrompt']
25
+
26
+ export const Config = Schema.object({
27
+ storage: Schema.object({
28
+ root: Schema.string().default('').description('Absolute memory root; empty uses $DSH_HOME/dsh-memory.'),
29
+ maxNoteBytes: Schema.natural().default(8192).description('Maximum rendered size of one note.'),
30
+ maxNotes: Schema.natural().default(200).description('Maximum notes per workspace space.'),
31
+ }).default({}),
32
+ spaces: Schema.object({
33
+ global: Schema.boolean().default(false).description('Reserved: shared global space (not implemented yet).'),
34
+ }).default({}),
35
+ extract: Schema.object({
36
+ enabled: Schema.boolean().default(true).description('Run the end-of-turn extraction pass.'),
37
+ minNewChars: Schema.natural().default(1500).description('Minimum new conversation text before extracting.'),
38
+ model: Schema.string().default('').description('Model id for extraction; empty uses the session model.'),
39
+ maxPerTurn: Schema.natural().default(3).description('Maximum notes written by one extraction.'),
40
+ }).default({}),
41
+ recall: Schema.object({
42
+ enabled: Schema.boolean().default(true).description('Inject relevant notes before answering.'),
43
+ strategy: Schema.string().default('lexical').description('lexical (default) or llm: how notes are chosen.'),
44
+ topK: Schema.natural().default(3).description('Maximum notes recalled per turn.'),
45
+ maxNoteBytes: Schema.natural().default(4096).description('Maximum bytes of one recalled note.'),
46
+ sessionBudgetBytes: Schema.natural().default(40960).description('Cumulative recall budget per session.'),
47
+ timeoutMs: Schema.natural().default(400).description('Recall deadline; skip silently when exceeded.'),
48
+ llmTimeoutMs: Schema.natural().default(2000).description('Deadline for the LLM selector used by strategy "llm".'),
49
+ }).default({}),
50
+ dream: Schema.object({
51
+ enabled: Schema.boolean().default(true).description('Consolidate notes automatically after enough sessions and time.'),
52
+ minHours: Schema.natural().default(24).description('Minimum hours since the last automatic consolidation.'),
53
+ minSessions: Schema.natural().default(5).description('Minimum distinct sessions seen since the last consolidation.'),
54
+ maxNotes: Schema.natural().default(60).description('Notes considered by one automatic pass.'),
55
+ maxDeletes: Schema.natural().default(5).description('Maximum deletions allowed in one automatic pass.'),
56
+ model: Schema.string().default('').description('Model id for automatic consolidation; empty uses the session model.'),
57
+ agent: Schema.boolean().default(true).description('Consolidate through a tool-capable subagent that can verify notes against the codebase; falls back to a single model call when unavailable.'),
58
+ provider: Schema.string().default('spawn').description('Subagent backend used by the consolidation agent (spawn or fork).'),
59
+ agentModel: Schema.string().default('').description('Model id for the consolidation subagent; empty inherits the parent selection.'),
60
+ agentTimeoutMs: Schema.natural().default(180000).description('Wall-clock budget for one consolidation subagent run.'),
61
+ backoffMinutes: Schema.natural().default(60).description('After a failed pass, wait this long before trying again.'),
62
+ }).default({}),
63
+ memoryMd: Schema.object({
64
+ enabled: Schema.boolean().default(true).description('Maintain a generated MEMORY.md index in every space.'),
65
+ maxEntries: Schema.natural().default(100).description('Most entries written to MEMORY.md.'),
66
+ maxLineChars: Schema.natural().default(240).description('Per-line character cap for index entries.'),
67
+ maxChars: Schema.natural().default(12000).description('Total character cap for MEMORY.md.'),
68
+ inject: Schema.boolean().default(true).description('Inject a bounded index once per session.'),
69
+ injectMaxEntries: Schema.natural().default(20).description('Most index entries in the injected copy.'),
70
+ injectMaxChars: Schema.natural().default(2000).description('Character cap for the injected index (roughly 1-1.5k tokens for Chinese).'),
71
+ }).default({}),
72
+ ui: Schema.object({
73
+ enabled: Schema.boolean().default(true).description('Register the memory page in the right sidebar.'),
74
+ }).default({}),
75
+ })
76
+
77
+ const MEMORY_DIR_LABEL = '<workspace>'
78
+
79
+ function cwdOf(session) {
80
+ const cwd = session?.header?.cwd
81
+ return typeof cwd === 'string' && cwd !== '' ? cwd : process.cwd()
82
+ }
83
+
84
+ function spaceOf(session) {
85
+ const dir = cwdOf(session)
86
+ return { key: spaceKeyFor(dir), dir }
87
+ }
88
+
89
+ function memoryDirFor(root, key) {
90
+ return `${root.replace(/\/+$/, '')}/spaces/${key}`
91
+ }
92
+
93
+ function textOfMessage(message) {
94
+ const content = message?.content
95
+ if (!Array.isArray(content)) return ''
96
+ return content
97
+ .filter(block => block !== null && typeof block === 'object' && block.type === 'text')
98
+ .map(block => String(block.text ?? ''))
99
+ .join('\n')
100
+ .trim()
101
+ }
102
+
103
+ function summarizeWrite(result) {
104
+ const parts = [`${result.created ? 'created' : 'updated'} ${result.file}`, `${result.bytes} bytes`]
105
+ if (result.hint !== undefined) parts.push(result.hint)
106
+ return parts.join(' · ')
107
+ }
108
+
109
+ export function apply(ctx, rawConfig) {
110
+ const config = normalizeConfig(rawConfig)
111
+ const root = resolveStorageRoot(config)
112
+ const store = createStore({
113
+ root,
114
+ maxNoteBytes: config.storage.maxNoteBytes,
115
+ maxNotes: config.storage.maxNotes,
116
+ memoryIndex: config.memoryMd,
117
+ })
118
+ const displayDir = memoryDirFor(root, MEMORY_DIR_LABEL)
119
+ const globalEnabled = config.spaces.global === true
120
+
121
+ /** Spaces this session may read: always its workspace, plus global when enabled. */
122
+ function spacesFor(spaceKey) {
123
+ const spaces = [{ key: spaceKey, scope: 'workspace' }]
124
+ if (globalEnabled) spaces.push({ key: GLOBAL_SPACE, scope: 'global' })
125
+ return spaces
126
+ }
127
+
128
+ /** A tool's requested scope, downgraded to the workspace when global is off. */
129
+ function targetSpaceKey(spaceKey, scope) {
130
+ return scope === 'global' && globalEnabled ? GLOBAL_SPACE : spaceKey
131
+ }
132
+
133
+ ctx.effect(
134
+ () =>
135
+ ctx.systemPrompt.section({
136
+ name: 'dsh-memory:guidance',
137
+ order: SECTION_ORDER,
138
+ text: buildMemorySection({
139
+ displayDir,
140
+ maxNoteBytes: config.storage.maxNoteBytes,
141
+ globalEnabled: config.spaces.global,
142
+ }),
143
+ }),
144
+ 'dsh-memory: guidance section',
145
+ )
146
+
147
+ /** Live model selection of the agent that owns a session, if it is still live. */
148
+ function selectionFor(session) {
149
+ const agents = ctx.get?.('agents')?.list?.() ?? []
150
+ const entry = agents.find(candidate => (candidate?.agent ?? candidate)?.session === session)
151
+ const liveAgent = entry?.agent ?? entry
152
+ const selection = liveAgent?.model?.current?.()
153
+ if (selection?.provider === undefined || selection?.model === undefined) return null
154
+ return { provider: selection.provider, model: selection.model }
155
+ }
156
+
157
+ const extractor = createExtractor({
158
+ store,
159
+ config,
160
+ log: ctx.logger,
161
+ spaceOf,
162
+ digestMaxBytes: 16384,
163
+ getLlm: () => (ctx.get === undefined ? undefined : ctx.get('llm')),
164
+ getRoute: session => {
165
+ const selection = selectionFor(session)
166
+ if (config.extract.model !== '') {
167
+ return { provider: selection?.provider ?? 'deepseek', model: config.extract.model }
168
+ }
169
+ return selection
170
+ },
171
+ })
172
+
173
+ /**
174
+ * Live root Agents, keyed by session id. The consolidation subagent needs a real
175
+ * `parent` Agent, and only a pre-step gives us one; turn/end alone carries a
176
+ * Session. Stale entries are harmless — a replaced parent is rejected at start.
177
+ */
178
+ const liveAgents = new Map()
179
+ function rememberAgent(agent) {
180
+ const id = agent?.session?.id
181
+ if (typeof id !== 'string' || id === '') return
182
+ liveAgents.set(id, agent)
183
+ if (liveAgents.size > 64) liveAgents.delete(liveAgents.keys().next().value)
184
+ }
185
+ function liveAgentFor(session) {
186
+ const id = session?.id
187
+ if (typeof id === 'string' && id !== '' && liveAgents.has(id)) return liveAgents.get(id)
188
+ for (const entry of ctx.get?.('agents')?.list?.() ?? []) {
189
+ const live = entry?.agent ?? entry
190
+ if (live?.session === session) return live
191
+ }
192
+ return null
193
+ }
194
+
195
+ const dreamAgent = createDreamAgentRunner({
196
+ config,
197
+ log: ctx.logger,
198
+ getSubagents: () => (ctx.get === undefined ? undefined : ctx.get('subagents')),
199
+ getParent: session => liveAgentFor(session),
200
+ getCodeRoot: session => cwdOf(session),
201
+ getSessionHints: () => Object.keys(autoDream.stateOf().sessions),
202
+ })
203
+
204
+ /**
205
+ * The plan producer handed to autoDream. It runs the subagent, then applies the
206
+ * same hard limits the single-call path enforces — plus a shrink guard, because
207
+ * the agent path hands out a manifest instead of bodies.
208
+ */
209
+ async function produceDreamPlan(input) {
210
+ const plan = await dreamAgent.respond(input)
211
+ if (plan === null || typeof plan !== 'object' || typeof plan.error === 'string') return plan
212
+ const notes = Array.isArray(input?.notes) ? input.notes : []
213
+ let sizes = input?.sizes instanceof Map ? input.sizes : new Map()
214
+ if (sizes.size === 0) {
215
+ for (const note of notes) {
216
+ if (Number.isFinite(note?.chars) && note.chars > 0) sizes.set(note.file, note.chars)
217
+ }
218
+ }
219
+ const validated = validateDreamAgentPlan({
220
+ plan,
221
+ prompted: new Set(notes.map(note => note.file)),
222
+ truncated: new Set(),
223
+ sizes,
224
+ maxOps: input?.maxOps,
225
+ maxDeletes: config.dream.maxDeletes,
226
+ })
227
+ if (validated.rejected.length > 0) {
228
+ ctx.logger?.warn?.('dsh-memory: dream rejected %d unsupported change(s): %o', validated.rejected.length, validated.rejected)
229
+ }
230
+ return { merges: validated.merges, deletes: validated.deletes, conflicts: validated.conflicts }
231
+ }
232
+
233
+ const autoDream = createAutoDream({
234
+ store,
235
+ config,
236
+ log: ctx.logger,
237
+ statePath: join(root, AUTO_DREAM_STATE_FILE),
238
+ getLlm: () => (ctx.get === undefined ? undefined : ctx.get('llm')),
239
+ getRoute: session => selectionFor(session),
240
+ respond: config.dream.agent === false ? undefined : produceDreamPlan,
241
+ memoryDirOf: spaceKey => memoryDirFor(root, spaceKey),
242
+ backoffMs: config.dream.backoffMinutes * 60 * 1000,
243
+ })
244
+
245
+ // The page is global, but "current" means "the workspace of the session that
246
+ // touched the plugin most recently". Updated on every session event.
247
+ let lastActiveCwd = ''
248
+
249
+ ctx.on('session/event', (session, event) => {
250
+ const cwd = session?.header?.cwd
251
+ if (typeof cwd === 'string' && cwd !== '') lastActiveCwd = cwd
252
+ try {
253
+ extractor.onSessionEvent(session, event)
254
+ } catch (error) {
255
+ ctx.logger?.warn?.('dsh-memory: extraction listener failed: %o', error)
256
+ }
257
+ // Automatic consolidation only counts root sessions; a subagent's turns are
258
+ // work, not separate visits to the memory.
259
+ if (session?.header?.delegationDepth > 0) return
260
+ try {
261
+ autoDream.observe(session?.id)
262
+ } catch {
263
+ // best effort: a bookkeeping failure must not affect the turn
264
+ }
265
+ if (event?.type === 'turn/end') {
266
+ void autoDream
267
+ .maybeRun({ session, spaceKey: spaceOf(session) })
268
+ .catch(error => ctx.logger?.warn?.('dsh-memory: automatic dream failed: %o', error))
269
+ }
270
+ })
271
+
272
+ /** Route captured for the current turn; the LLM selector takes no arguments. */
273
+ let recallRoute = null
274
+ const recall = createRecall({
275
+ store,
276
+ config,
277
+ getLlm: () => (ctx.get === undefined ? undefined : ctx.get('llm')),
278
+ getRoute: () => recallRoute,
279
+ })
280
+ /** @type {Map<string, Set<string>>} */
281
+ const surfaced = new Map()
282
+ /** @type {Map<string, number>} */
283
+ const spentBytes = new Map()
284
+ /** @type {Map<string, number>} Last turn that ran recall, so later steps skip. */
285
+ const recalledTurn = new Map()
286
+
287
+ /** Recall is best-effort: any failure must leave the turn untouched. */
288
+ async function injectRecall({ agent, messages, turn, signal, decision }) {
289
+ if (
290
+ config.recall.enabled !== true ||
291
+ decision.kind !== 'enter' ||
292
+ agent === undefined ||
293
+ agent === null ||
294
+ signal?.aborted === true
295
+ ) {
296
+ return decision
297
+ }
298
+ const sessionId = String(agent.session?.id ?? '')
299
+ const turnNumber = Number.isFinite(Number(turn)) ? Number(turn) : null
300
+ if (turnNumber !== null) {
301
+ const previous = recalledTurn.get(sessionId)
302
+ if (previous !== undefined && turnNumber <= previous) return decision
303
+ recalledTurn.set(sessionId, turnNumber)
304
+ if (recalledTurn.size > 200) recalledTurn.delete(recalledTurn.keys().next().value)
305
+ }
306
+ const query = messages.map(textOfMessage).filter(text => text !== '').join('\n')
307
+ if (query === '') return decision
308
+ const seen = surfaced.get(sessionId) ?? new Set()
309
+ const spent = spentBytes.get(sessionId) ?? 0
310
+ const remaining = config.recall.sessionBudgetBytes - spent
311
+ if (remaining <= 0) return decision
312
+ const space = spaceOf(agent.session)
313
+ const selection = agent.model?.current?.()
314
+ recallRoute =
315
+ selection?.provider === undefined || selection?.model === undefined
316
+ ? null
317
+ : { provider: selection.provider, model: selection.model }
318
+ const recallBudget =
319
+ config.recall.strategy === 'llm' ? config.recall.llmTimeoutMs + 400 : config.recall.timeoutMs
320
+ const picked = await withTimeout(
321
+ recall.collect({ spaces: spacesFor(space.key), query, exclude: seen, budgetBytes: remaining }),
322
+ recallBudget,
323
+ )
324
+ if (picked === undefined || picked.notes.length === 0) return decision
325
+ const text = formatRecall(picked.notes)
326
+ if (text === '') return decision
327
+ for (const id of picked.files) seen.add(id)
328
+ surfaced.set(sessionId, seen)
329
+ spentBytes.set(sessionId, spent + picked.bytes)
330
+ if (surfaced.size > 200) surfaced.delete(surfaced.keys().next().value)
331
+ if (spentBytes.size > 200) spentBytes.delete(spentBytes.keys().next().value)
332
+ const context = createUserMessage({
333
+ content: [{ type: 'text', text }],
334
+ source: { kind: 'dsh-memory', form: 'notice', summary: `recalled ${picked.notes.length} memory note(s)` },
335
+ })
336
+ return { ...decision, messages: [...decision.messages, context] }
337
+ }
338
+
339
+ /** Sessions that already received the bounded MEMORY.md overview. */
340
+ const indexInjected = new Set()
341
+
342
+ /**
343
+ * Inject the generated index once per session. The index is names and
344
+ * one-line descriptions only; full bodies still come from recall or tools.
345
+ */
346
+ async function injectMemoryIndex({ agent, decision }) {
347
+ if (config.memoryMd.enabled !== true || config.memoryMd.inject !== true) return decision
348
+ if (agent === undefined || agent === null) return decision
349
+ const sessionId = String(agent.session?.id ?? '')
350
+ if (sessionId === '' || indexInjected.has(sessionId)) return decision
351
+ const space = spaceOf(agent.session)
352
+ const notes = await store.listNotes(space.key).catch(() => [])
353
+ if (notes.length === 0) return decision
354
+ const text = buildIndexInjection(notes, {
355
+ label: space.key,
356
+ maxEntries: config.memoryMd.injectMaxEntries,
357
+ maxLineChars: config.memoryMd.maxLineChars,
358
+ maxChars: config.memoryMd.injectMaxChars,
359
+ })
360
+ if (text === '') return decision
361
+ const bytes = Buffer.byteLength(text, 'utf8')
362
+ const spent = spentBytes.get(sessionId) ?? 0
363
+ if (spent + bytes > config.recall.sessionBudgetBytes) return decision
364
+ spentBytes.set(sessionId, spent + bytes)
365
+ if (spentBytes.size > 200) spentBytes.delete(spentBytes.keys().next().value)
366
+ indexInjected.add(sessionId)
367
+ if (indexInjected.size > 200) indexInjected.delete(indexInjected.keys().next().value)
368
+ const message = createUserMessage({
369
+ content: [{ type: 'text', text }],
370
+ source: { kind: 'dsh-memory', form: 'notice', summary: `injected memory index (${notes.length} notes)` },
371
+ })
372
+ return { ...decision, messages: [...decision.messages, message] }
373
+ }
374
+
375
+ ctx.on('agent/pre-step', async ({ agent, messages, turn, signal }, next) => {
376
+ rememberAgent(agent)
377
+ const decision = await next()
378
+ let withIndex = decision
379
+ try {
380
+ withIndex = await injectMemoryIndex({ agent, decision })
381
+ } catch (error) {
382
+ ctx.logger?.warn?.('dsh-memory: index injection skipped: %o', error)
383
+ }
384
+ try {
385
+ return await injectRecall({ agent, messages, turn, signal, decision: withIndex })
386
+ } catch (error) {
387
+ ctx.logger?.warn?.('dsh-memory: recall skipped: %o', error)
388
+ return withIndex
389
+ }
390
+ })
391
+
392
+ const handlers = createHandlers({
393
+ store,
394
+ rank: async (spaceKey, query, limit) => {
395
+ const notes = await store.listNotes(spaceKey)
396
+ return rankNotes(query, notes).slice(0, limit)
397
+ },
398
+ })
399
+
400
+ ctx.tools.register(
401
+ defineTool({
402
+ name: 'memory_note',
403
+ description:
404
+ 'Save or update one durable memory note for this workspace (user preferences, feedback, project context, external references). Use it when the user asks you to remember something or when a fact will matter in later sessions.',
405
+ parameters: {
406
+ name: { type: 'string', required: true, description: 'Short title, unique per topic.' },
407
+ description: { type: 'string', required: true, description: 'One line used to decide relevance in future sessions.' },
408
+ type: { type: 'string', required: true, enum: ['user', 'feedback', 'project', 'reference'] },
409
+ body: { type: 'string', required: true, description: 'Markdown body; feedback/project notes include "**Why:**" and "**How to apply:**".' },
410
+ scope: { type: 'string', enum: ['workspace', 'global'], description: 'Defaults to this workspace. Use global only for facts useful in every project, and only when global memory is enabled.' },
411
+ },
412
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
413
+ async execute(args, exec) {
414
+ const space = spaceOf(exec.agent?.session)
415
+ const result = await handlers.write({
416
+ spaceKey: targetSpaceKey(space.key, args.scope),
417
+ name: args.name,
418
+ description: args.description,
419
+ type: args.type,
420
+ body: args.body,
421
+ origin: 'agent',
422
+ sessionId: String(exec.agent?.session?.id ?? ''),
423
+ })
424
+ return summarizeWrite(result)
425
+ },
426
+ }),
427
+ )
428
+
429
+ ctx.tools.register(
430
+ defineTool({
431
+ name: 'memory_search',
432
+ description:
433
+ 'Search this workspace memory notes before answering questions about earlier decisions, prior work, or user preferences. Returns short excerpts; read the note file for full content.',
434
+ parameters: {
435
+ query: { type: 'string', description: 'Search terms, usually a short phrase.' },
436
+ type: { type: 'string', enum: ['user', 'feedback', 'project', 'reference'], description: 'Optional type filter.' },
437
+ limit: { type: 'integer', description: 'Maximum notes to return (1-20).' },
438
+ },
439
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
440
+ async execute(args, exec) {
441
+ const space = spaceOf(exec.agent?.session)
442
+ const result = await handlers.search({
443
+ spaces: spacesFor(space.key),
444
+ query: args.query ?? '',
445
+ type: args.type,
446
+ limit: args.limit,
447
+ })
448
+ if (result.notes.length === 0) return 'No matching memory notes.'
449
+ return result.notes
450
+ .map(note => {
451
+ const where = note.scope === 'global' ? ' [global]' : ''
452
+ return `- ${note.name} [${note.type}]${where} (${note.file})\n ${note.description}\n ${note.excerpt}`
453
+ })
454
+ .join('\n')
455
+ },
456
+ }),
457
+ )
458
+
459
+ ctx.tools.register(
460
+ defineTool({
461
+ name: 'memory_forget',
462
+ description:
463
+ 'Delete one memory note from this workspace when the user asks you to forget something or when a note is wrong and should not be corrected in place. Use memory_search first to find the file name.',
464
+ parameters: {
465
+ file: { type: 'string', required: true, description: 'Note file name exactly as memory_search returned it, e.g. "user_role.md".' },
466
+ scope: { type: 'string', enum: ['workspace', 'global'], description: 'Which space the note lives in; defaults to this workspace.' },
467
+ },
468
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
469
+ async execute(args, exec) {
470
+ const space = spaceOf(exec.agent?.session)
471
+ const result = await handlers.remove({ spaceKey: targetSpaceKey(space.key, args.scope), file: args.file })
472
+ return result.removed ? `deleted ${args.file}` : `no such note: ${args.file}`
473
+ },
474
+ }),
475
+ )
476
+
477
+ // /dream — a manual consolidation pass. The handler only prepares the prompt:
478
+ // the model edits notes with the same tools it uses during normal work.
479
+ ctx.inject(['commands'], commandCtx => {
480
+ commandCtx.effect(
481
+ () =>
482
+ commandCtx.commands.register({
483
+ definitionId: 'dsh-memory-dream',
484
+ name: 'dream',
485
+ description: '整理当前工作区的记忆笔记:合并重复、纠正过期、修剪冗余',
486
+ input: { hint: '[focus]' },
487
+ handler: async ({ agent, rawInput }) => {
488
+ if (agent === undefined || agent === null) {
489
+ return { kind: 'error', text: '没有可用的会话,无法整理记忆。' }
490
+ }
491
+ const space = spaceOf(agent.session)
492
+ let hints = []
493
+ try {
494
+ hints = await collectDreamHints({
495
+ sessionQuery: ctx.get?.('sessionQuery'),
496
+ currentSessionId: String(agent.session?.id ?? ''),
497
+ limit: 5,
498
+ })
499
+ } catch {
500
+ hints = []
501
+ }
502
+ let noteCount = 0
503
+ try {
504
+ noteCount = (await store.listNotes(space.key)).length
505
+ } catch {
506
+ noteCount = 0
507
+ }
508
+ const prompt = buildDreamPrompt({
509
+ memoryDir: memoryDirFor(root, space.key),
510
+ globalDir: memoryDirFor(root, GLOBAL_SPACE),
511
+ spaceLabel: space.key,
512
+ globalEnabled,
513
+ focus: String(rawInput ?? '').trim(),
514
+ sessionHints: hints,
515
+ noteCount,
516
+ maxNotes: config.storage.maxNotes,
517
+ maxNoteBytes: config.storage.maxNoteBytes,
518
+ })
519
+ try {
520
+ agent.followup(
521
+ createUserMessage({
522
+ content: [{ type: 'text', text: prompt }],
523
+ source: { kind: 'user' },
524
+ }),
525
+ )
526
+ } catch (error) {
527
+ ctx.logger?.warn?.('dsh-memory: dream followup failed: %o', error)
528
+ return { kind: 'error', text: '无法把整理任务送入会话。' }
529
+ }
530
+ return {
531
+ kind: 'success',
532
+ text: `开始整理记忆(${space.key})…完成后会给出整理摘要。`,
533
+ }
534
+ },
535
+ }),
536
+ 'dsh-memory: /dream command',
537
+ )
538
+ })
539
+
540
+ ctx.inject(['webServer'], webCtx => {
541
+ const handle = createApiHandler({
542
+ store,
543
+ currentSpaceKey: () => (lastActiveCwd === '' ? '' : spaceKeyFor(lastActiveCwd)),
544
+ globalEnabled,
545
+ listKnownSpaces: async () => {
546
+ const registry = webCtx.get?.('workspaceRegistry')
547
+ const spaces = registry?.list?.() ?? []
548
+ return spaces.map(space => ({
549
+ key: spaceKeyFor(space.path ?? space.id ?? ''),
550
+ title: space.title ?? undefined,
551
+ path: space.path ?? '',
552
+ }))
553
+ },
554
+ })
555
+ webCtx.effect(() => {
556
+ const disposers = []
557
+ for (const path of [`${API_PREFIX}/spaces`, `${API_PREFIX}/notes`, `${API_PREFIX}/note`, `${API_PREFIX}/index`]) {
558
+ disposers.push(webCtx.webServer.register({ kind: 'exact', path, handler: handle }))
559
+ }
560
+ return () => {
561
+ for (const dispose of disposers.reverse()) dispose?.()
562
+ }
563
+ }, 'dsh-memory: api routes')
564
+ })
565
+ }
566
+
567
+ function withTimeout(promise, ms) {
568
+ if (!Number.isFinite(ms) || ms <= 0) return promise
569
+ return new Promise((resolve, reject) => {
570
+ const timer = setTimeout(() => reject(new Error('memory recall timed out')), ms)
571
+ promise.then(
572
+ value => {
573
+ clearTimeout(timer)
574
+ resolve(value)
575
+ },
576
+ error => {
577
+ clearTimeout(timer)
578
+ reject(error)
579
+ },
580
+ )
581
+ })
582
+ }
package/locale/en.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "meta": {
3
+ "title": "Memory notes",
4
+ "description": "Workspace-scoped memory notes: capture, extract, recall, and browse them in a sidebar page.",
5
+ "detail": "docs/DETAIL.md"
6
+ },
7
+ "page": {
8
+ "tab.title": "Memory",
9
+ "guide.title": "Memory",
10
+ "guide.description": "Browse the memory notes of every workspace directory.",
11
+ "spaces.title": "Spaces",
12
+ "spaces.current": "Current",
13
+ "spaces.global": "Global",
14
+ "spaces.locked": "Coming soon",
15
+ "spaces.empty": "No spaces yet",
16
+ "spaces.count": "{count}",
17
+ "spaces.none": "—",
18
+ "notes.title": "Memory notes",
19
+ "notes.empty": "This directory has no memory yet.",
20
+ "notes.emptyHint": "Ask the assistant to remember something in a conversation and the note appears here.",
21
+ "notes.count": "{count} notes",
22
+ "notes.refresh": "Refresh",
23
+ "note.updatedAt": "Updated {time}",
24
+ "note.session": "Session {id}",
25
+ "note.noSession": "No source session",
26
+ "note.noDescription": "(no description)",
27
+ "state.loading": "Loading…",
28
+ "state.error.title": "Could not load",
29
+ "state.error.retry": "Retry",
30
+ "state.error.network": "Cannot reach the memory service. Check that the plugin is still running.",
31
+ "state.error.http": "The service returned {status}.",
32
+ "state.error.body": "The service returned an unreadable response.",
33
+ "state.error.timeout": "The request timed out. Try again.",
34
+ "detail.back": "Back",
35
+ "detail.file": "File",
36
+ "detail.notFound": "This note no longer exists; it may have been merged or deleted.",
37
+ "detail.bytes": "{bytes} bytes",
38
+ "badge.type.user": "User",
39
+ "badge.type.feedback": "Feedback",
40
+ "badge.type.project": "Project",
41
+ "badge.type.reference": "Reference",
42
+ "badge.origin.agent": "Written by a tool",
43
+ "badge.origin.extract": "Extracted automatically",
44
+ "badge.origin.dream": "Consolidated",
45
+ "index.badge": "Index",
46
+ "index.title": "MEMORY.md index",
47
+ "index.subtitle": "Index · {count} entries",
48
+ "index.open": "View index"
49
+ }
50
+ }