@goodandready/dsh-messenger-gateway 0.4.25 → 0.4.26

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/lib/commands.js CHANGED
@@ -24,6 +24,9 @@ export const DEFAULT_TELEGRAM_COMMANDS = [
24
24
  { command: 'fork', description: 'Fork session into new branch' },
25
25
  { command: 'export', description: 'Export history to Markdown' },
26
26
  { command: 'rewind', description: 'Rewind turns: /rewind [N]' },
27
+ { command: 'project', description: 'Bind or show topic workspace: /project' },
28
+ { command: 'memory', description: 'User memory facts: /memory [add <fact>]' },
29
+ { command: 'forget', description: 'Forget user memory: /forget <id|all>' },
27
30
  { command: 'cwd', description: 'Show working directory: /cwd' },
28
31
  { command: 'files', description: 'Workspace file explorer: /files [dir]' },
29
32
  { command: 'get', description: 'Download file to messenger: /get <path>' },
@@ -104,6 +107,9 @@ export const HELP_TEXT = [
104
107
  '',
105
108
  'đŸ› ī¸ <b>Tools, Files & Cron:</b>',
106
109
  'â€ĸ /skills / /tools — list active tools & skills',
110
+ 'â€ĸ /project — topic workspace binding (/project bind <path>)',
111
+ 'â€ĸ /memory — show remembered facts about you (/memory add <fact>)',
112
+ 'â€ĸ /forget <id|all> — delete stored user facts',
107
113
  'â€ĸ /cwd — show current working directory',
108
114
  'â€ĸ /files [dir] — workspace file explorer',
109
115
  'â€ĸ /get <path> — download file from workspace',
package/lib/config.js CHANGED
@@ -103,6 +103,15 @@ export const PluginConfig = z.object({
103
103
  maxChars: z.number().default(4000),
104
104
  voiceSummary: z.boolean().default(false).description('Speak concise TL;DR summary while full text is sent to chat'),
105
105
  }).volatile(),
106
+ memory: z.object({
107
+ enabled: z.boolean().default(true),
108
+ baseUrl: z.string().default('').description('Base URL for dsh-memory-brain service (default http://127.0.0.1:28080)'),
109
+ tokenEnv: z.string().default('MEMORY_BRAIN_TOKEN').description('Environment variable name containing the bearer token'),
110
+ token: z.string().role('secret').default('').description('Explicit bearer token if not using tokenEnv'),
111
+ autoInject: z.boolean().default(true).description('Automatically retrieve and inject user memories into agent turn context'),
112
+ budget: z.number().default(2000).description('Character budget for injected memories'),
113
+ timeoutMs: z.number().default(3500).description('HTTP request timeout in ms for memory-brain calls'),
114
+ }).default({ enabled: true }).volatile(),
106
115
  agent: z.object({
107
116
  provider: z.string().default(''),
108
117
  model: z.string().default(''),
@@ -1,4 +1,5 @@
1
- import { resolve, dirname } from 'node:path'
1
+ import { resolve, dirname, basename } from 'node:path'
2
+ import { realpathSync } from 'node:fs'
2
3
  import { fileURLToPath } from 'node:url'
3
4
  import { ensureContentArray } from './content-guard.js'
4
5
  import { t } from './locales/index.js'
@@ -12,8 +13,9 @@ import { listModelCatalog, buildProvidersKeyboard } from './models.js'
12
13
  import { normalizeHomeName, upsertHome, listHomes } from './homes.js'
13
14
  import { handleSetAlertCommand, handleAlertCommand } from './alerts.js'
14
15
  import { HELP_TEXT } from './commands.js'
15
- import { resolveEffectiveCwd } from './workspace.js'
16
+ import { resolveEffectiveCwd, getCwdWarning, inspectGitWorkspace, registerSessionInWorkspace } from './workspace.js'
16
17
  import { escapeHtml } from './telegram-format.js'
18
+ import { rememberUserFact, listUserMemories, forgetUserMemory } from './memory-brain.js'
17
19
 
18
20
 
19
21
  export function releaseChatTurn(chat) {
@@ -252,14 +254,163 @@ export async function handleGatewayCommand(gw, key, text, input) {
252
254
  }
253
255
  }
254
256
 
257
+ if (cmd === '/project') {
258
+ const sub = parts[1]?.toLowerCase()
259
+ if (sub === 'bind') {
260
+ const targetPath = parts[2]
261
+ if (!targetPath) {
262
+ return reply('Usage: <code>/project bind &lt;path&gt; [role]</code>\nExample: <code>/project bind /home/vadim/my-app coder</code>')
263
+ }
264
+ const warning = getCwdWarning(targetPath)
265
+ if (warning) {
266
+ return reply(`❌ <b>Invalid workspace directory:</b>\n${escapeHtml(warning)}`)
267
+ }
268
+ let realCwd = targetPath
269
+ try { realCwd = realpathSync(resolve(targetPath)) } catch { realCwd = resolve(targetPath) }
270
+ const gitInfo = inspectGitWorkspace(realCwd)
271
+ const roleArg = parts[3]?.toLowerCase()
272
+ const validRole = roleArg && getPersona(roleArg) ? roleArg : null
273
+
274
+ gw.topicWorkspaces?.set(chatId, threadId, {
275
+ path: realCwd,
276
+ name: basename(realCwd),
277
+ role: validRole,
278
+ worktree: gitInfo.isWorktree,
279
+ })
280
+
281
+ if (validRole) {
282
+ gw.personas?.set(chatId, validRole, threadId)
283
+ }
284
+
285
+ const chat = gw.chats.get(key)
286
+ if (chat?.agent?.session?.id) {
287
+ registerSessionInWorkspace(gw.ctx, chat.agent.session.id, realCwd, gw.ctx?.logger).catch(() => {})
288
+ }
289
+
290
+ const lines = [
291
+ `✅ <b>Workspace bound to topic:</b>`,
292
+ `📁 Directory: <code>${escapeHtml(realCwd)}</code>`,
293
+ ]
294
+ if (gitInfo.isWorktree) lines.push(`đŸŒŋ Git Worktree: <code>detected</code>`)
295
+ else if (gitInfo.isGit) lines.push(`đŸ“Ļ Git Repository: <code>main repo</code>`)
296
+ if (validRole) lines.push(`🎭 Persona role: <b>${validRole}</b>`)
297
+ return reply(lines.join('\n'))
298
+ }
299
+
300
+ if (sub === 'unbind' || sub === 'reset' || sub === 'clear') {
301
+ const removed = gw.topicWorkspaces?.delete(chatId, threadId)
302
+ if (removed) {
303
+ return reply('✅ <b>Workspace unbind:</b> topic reverted to default workspace.')
304
+ }
305
+ return reply('â„šī¸ No custom workspace was bound to this topic.')
306
+ }
307
+
308
+ if (sub === 'list') {
309
+ const list = gw.topicWorkspaces?.list(chatId) || []
310
+ if (!list.length) {
311
+ return reply('â„šī¸ No topics in this chat have bound workspaces.')
312
+ }
313
+ const lines = ['📁 <b>Bound Topic Workspaces:</b>\n']
314
+ for (const item of list) {
315
+ const tLabel = item.threadId ? `Topic #${item.threadId}` : 'Main Chat'
316
+ const roleLabel = item.role ? ` (role: ${item.role})` : ''
317
+ lines.push(`â€ĸ <b>${tLabel}</b>: <code>${escapeHtml(item.path)}</code>${roleLabel}`)
318
+ }
319
+ return reply(lines.join('\n'))
320
+ }
321
+
322
+ const bound = gw.topicWorkspaces?.get(chatId, threadId)
323
+ const effective = gw.resolveEffectiveCwdFor ? gw.resolveEffectiveCwdFor(chatId, threadId) : resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger)
324
+ const lines = [
325
+ `📁 <b>Project Workspace Status:</b>`,
326
+ ]
327
+ if (bound) {
328
+ lines.push(`â€ĸ Bound path: <code>${escapeHtml(bound.path)}</code>`)
329
+ if (bound.worktree) lines.push(`â€ĸ Mode: đŸŒŋ Git Worktree`)
330
+ if (bound.role) lines.push(`â€ĸ Bound role: <b>${bound.role}</b>`)
331
+ lines.push(`â€ĸ Bound since: <code>${bound.boundAt}</code>`)
332
+ } else {
333
+ lines.push(`â€ĸ Current workspace: <code>${escapeHtml(effective)}</code> (default)`)
334
+ lines.push(`â€ĸ Status: <i>Not bound to dedicated project</i>`)
335
+ }
336
+ lines.push('\n<b>Commands:</b>')
337
+ lines.push('â€ĸ <code>/project bind &lt;path&gt; [role]</code> — bind topic to directory or worktree')
338
+ lines.push('â€ĸ <code>/project unbind</code> — reset topic to default workspace')
339
+ lines.push('â€ĸ <code>/project list</code> — view all topic bindings')
340
+ return reply(lines.join('\n'))
341
+ }
342
+
343
+ if (cmd === '/memory') {
344
+ const sub = parts[1]?.toLowerCase()
345
+ if (sub === 'add') {
346
+ const factText = parts.slice(2).join(' ').trim()
347
+ if (!factText) {
348
+ return reply('Usage: <code>/memory add &lt;fact&gt;</code>\nExample: <code>/memory add I prefer concise answers in Python</code>')
349
+ }
350
+ const res = await rememberUserFact({
351
+ config: gw.config?.memory,
352
+ userId,
353
+ content: factText,
354
+ })
355
+ if (!res.ok) {
356
+ return reply(`❌ Failed to store memory: ${escapeHtml(res.error || 'unknown error')}`)
357
+ }
358
+ return reply(`🧠 <b>Memory remembered:</b>\n<i>${escapeHtml(factText)}</i>`)
359
+ }
360
+
361
+ const listRes = await listUserMemories({
362
+ config: gw.config?.memory,
363
+ userId,
364
+ limit: 25,
365
+ })
366
+ if (!listRes.ok) {
367
+ return reply(`âš ī¸ Memory service unavailable: ${escapeHtml(listRes.error || 'could not connect')}`)
368
+ }
369
+ if (!listRes.items || !listRes.items.length) {
370
+ return reply(`🧠 <b>User Memory (ID: <code>${escapeHtml(String(userId))}</code>):</b>\n<i>No stored facts found.</i>\n\nAdd one: <code>/memory add &lt;fact&gt;</code>`)
371
+ }
372
+ const lines = [
373
+ `🧠 <b>User Memory Profile (ID: <code>${escapeHtml(String(userId))}</code>):</b>`,
374
+ '',
375
+ ...listRes.items.map((it, idx) => `${idx + 1}. [<code>${escapeHtml(it.id.slice(0, 8))}</code>] ${escapeHtml(it.content)}`),
376
+ '',
377
+ 'â€ĸ Add fact: <code>/memory add &lt;fact&gt;</code>',
378
+ 'â€ĸ Forget fact: <code>/forget &lt;id&gt;</code>',
379
+ 'â€ĸ Clear all: <code>/forget all</code>',
380
+ ]
381
+ return reply(lines.join('\n'))
382
+ }
383
+
384
+ if (cmd === '/forget') {
385
+ const targetId = parts[1]?.trim()
386
+ if (!targetId) {
387
+ return reply('Usage: <code>/forget &lt;id|all&gt;</code>\nExample: <code>/forget 95b82eb8</code> or <code>/forget all</code>\nRun <code>/memory</code> to view memory IDs.')
388
+ }
389
+ const forgetRes = await forgetUserMemory({
390
+ config: gw.config?.memory,
391
+ userId,
392
+ memoryId: targetId,
393
+ })
394
+ if (!forgetRes.ok) {
395
+ return reply(`❌ Failed to forget: ${escapeHtml(forgetRes.error || 'unknown error')}`)
396
+ }
397
+ if (targetId.toLowerCase() === 'all') {
398
+ return reply(`đŸ—‘ī¸ Forgotten ${forgetRes.count || 0} user memor${forgetRes.count === 1 ? 'y' : 'ies'}.`)
399
+ }
400
+ return reply(`đŸ—‘ī¸ Forgotten memory <code>${escapeHtml(targetId)}</code>.`)
401
+ }
402
+
255
403
  if (cmd === '/cwd') {
256
404
  const chat = gw.chats.get(key)
257
- const sessionCwd = chat?.agent?.meta?.cwd || chat?.agent?.session?.meta?.cwd || resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger)
405
+ const sessionCwd = chat?.agent?.meta?.cwd || chat?.agent?.session?.meta?.cwd || (gw.resolveEffectiveCwdFor ? gw.resolveEffectiveCwdFor(chatId, threadId) : resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger))
406
+ const bound = gw.topicWorkspaces?.get(chatId, threadId)
258
407
  const configuredCwd = gw.config.agent?.cwd || ''
259
408
  const lines = [
260
409
  `📁 <b>Working Directory:</b> <code>${escapeHtml(sessionCwd)}</code>`,
261
410
  ]
262
- if (configuredCwd) {
411
+ if (bound) {
412
+ lines.push(`đŸŒŋ Topic binding: <code>${escapeHtml(bound.path)}</code>${bound.worktree ? ' (worktree)' : ''}`)
413
+ } else if (configuredCwd) {
263
414
  lines.push(`âš™ī¸ Configured: <code>${escapeHtml(configuredCwd)}</code>`)
264
415
  } else {
265
416
  lines.push(`â„šī¸ Default: host launch directory`)
@@ -269,14 +420,14 @@ export async function handleGatewayCommand(gw, key, text, input) {
269
420
 
270
421
  if (cmd === '/files') {
271
422
  const subPath = parts.slice(1).join(' ').trim() || '.'
272
- const agentCwd = resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger)
423
+ const agentCwd = (gw.resolveEffectiveCwdFor ? gw.resolveEffectiveCwdFor(chatId, threadId) : resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger))
273
424
  const res = await handleFilesCommand(agentCwd, subPath)
274
425
  return reply(res.text)
275
426
  }
276
427
 
277
428
  if (cmd === '/get') {
278
429
  const targetRel = parts.slice(1).join(' ').trim()
279
- const agentCwd = resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger)
430
+ const agentCwd = (gw.resolveEffectiveCwdFor ? gw.resolveEffectiveCwdFor(chatId, threadId) : resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger))
280
431
  const maxDocBytes = Number(gw.config.media?.maxDocBytes) || 50 * 1024 * 1024
281
432
  const res = await handleGetCommand(agentCwd, targetRel, maxDocBytes)
282
433
  return reply(res.files ? { text: res.text, files: res.files } : res.text)
@@ -15,6 +15,7 @@ import {
15
15
  buildStreamPreview, formatProgressLine, createEditScheduler, startTypingHeartbeat, parseReasoningStream
16
16
  } from './stream.js'
17
17
  import { escapeHtml } from './telegram-format.js'
18
+ import { recallUserMemories, recordTurnMemory } from './memory-brain.js'
18
19
 
19
20
  const PLUGIN = 'dsh-messenger-gateway'
20
21
 
@@ -135,9 +136,23 @@ export async function answerApproval(gw, chatKeyValue, req, next) {
135
136
  }
136
137
 
137
138
  export async function buildUserContent(gw, input, signal) {
138
- const { text, attachments = [], replyText, steer, personaOverride } = input
139
+ const { text, attachments = [], replyText, steer, personaOverride, userId } = input
139
140
  const parts = []
140
141
  parts.push(String(gw.config.agent?.instructionPrefix || MESSENGER_RELAY_INSTRUCTION))
142
+ if (gw.config?.memory?.enabled !== false && gw.config?.memory?.autoInject !== false && userId) {
143
+ try {
144
+ const recalled = await recallUserMemories({
145
+ config: gw.config.memory,
146
+ userId,
147
+ query: text || replyText || '',
148
+ budget: gw.config.memory?.budget,
149
+ signal,
150
+ })
151
+ if (recalled) parts.push(recalled)
152
+ } catch (memErr) {
153
+ gw.ctx?.logger?.debug?.(`[memory-brain] recall error: ${memErr?.message || memErr}`)
154
+ }
155
+ }
141
156
  const activePersonaId = personaOverride || gw.personas.getPersonaForChat(input.chatId, input.threadId)
142
157
  const activePersona = getPersona(activePersonaId)
143
158
  if (activePersona?.instruction) {
@@ -348,6 +363,17 @@ export async function runGatewayTurn(gw, chat, input, signal) {
348
363
  }
349
364
  }
350
365
  }
366
+ if (gw.config?.memory?.enabled !== false && userId && answer && input.text) {
367
+ recordTurnMemory({
368
+ config: gw.config.memory,
369
+ userId,
370
+ userText: input.text,
371
+ assistantText: answer,
372
+ logger: gw.ctx?.logger,
373
+ }).catch?.((recErr) => {
374
+ gw.ctx?.logger?.debug?.(`[memory-brain] recordTurnMemory error: ${recErr?.message || recErr}`)
375
+ })
376
+ }
351
377
  } catch (err) {
352
378
  if (!signal?.aborted) {
353
379
  gw.sendAlert('error', {
package/lib/gateway.js CHANGED
@@ -29,7 +29,9 @@ import {
29
29
  restoreSkillGesture,
30
30
  } from './forum-mirror.js'
31
31
  import { resolveInternalBaseUrl } from './config.js'
32
- import { resolveEffectiveCwd, registerSessionInWorkspace } from './workspace.js'
32
+ import { resolveEffectiveCwd, registerSessionInWorkspace, createTopicWorkspaceStore, getCwdWarning } from './workspace.js'
33
+ import { realpathSync } from 'node:fs'
34
+ import { resolve } from 'node:path'
33
35
 
34
36
 
35
37
  const PLUGIN = 'dsh-messenger-gateway'
@@ -59,6 +61,7 @@ export class Gateway {
59
61
  this.chatTts = createVoicePrefs(join(home, 'messenger-gateway', 'chat-tts.json'), { logger: this.logger })
60
62
  this.muted = createVoicePrefs(join(home, 'messenger-gateway', 'muted.json'), { logger: this.logger })
61
63
  this.personas = createPersonaStore(join(home, 'messenger-gateway', 'personas.json'), { logger: this.logger })
64
+ this.topicWorkspaces = createTopicWorkspaceStore(join(home, 'messenger-gateway', 'topic-workspaces.json'), { logger: this.logger })
62
65
  this.chatLocales = createVoicePrefs(join(home, 'messenger-gateway', 'chat-locales.json'), { logger: this.logger })
63
66
  this.scheduler = createScheduler(join(home, 'messenger-gateway', 'scheduled.json'), async (task) => {
64
67
  const target = {
@@ -571,10 +574,27 @@ export class Gateway {
571
574
  return { provider: provider || selection.provider, model: model || selection.model }
572
575
  }
573
576
 
577
+ resolveEffectiveCwdFor(chatId, threadId = 0) {
578
+ if (this.topicWorkspaces) {
579
+ const bound = this.topicWorkspaces.get(chatId, threadId)
580
+ if (bound?.path) {
581
+ const warning = getCwdWarning(bound.path)
582
+ if (!warning) {
583
+ try {
584
+ return realpathSync(resolve(bound.path))
585
+ } catch {
586
+ return resolve(bound.path)
587
+ }
588
+ }
589
+ }
590
+ }
591
+ return resolveEffectiveCwd(this.config.agent?.cwd, this.ctx?.logger)
592
+ }
593
+
574
594
  async createChat(key, input, existingSessionId) {
575
595
  const { provider, model } = this.resolveAgentModel()
576
596
  const agentCfg = this.config.agent || {}
577
- const cwd = resolveEffectiveCwd(agentCfg.cwd, this.ctx.logger)
597
+ const cwd = this.resolveEffectiveCwdFor(input.chatId, input.threadId)
578
598
  const self = this
579
599
  const agents = this.ctx.get?.('agents') || this.ctx.agents
580
600
  const targetSessionId = existingSessionId ? SessionId(existingSessionId) : SessionId(`msgw-${randomUUID()}`)
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Companion client for dsh-memory-brain service (#152).
3
+ *
4
+ * Implements persistent user memory and profile context over memory-brain's
5
+ * JSON-RPC /mcp and REST interface:
6
+ * - Scoped strictly to `user:<userId>` to prevent cross-user context leakage.
7
+ * - Non-blocking, fail-open: gateway turns never fail if memory-brain is offline.
8
+ * - Native Node 20 fetch without external dependencies.
9
+ */
10
+
11
+ export function resolveMemoryConfig(config) {
12
+ const cfg = config || {}
13
+ const tokenEnv = cfg.tokenEnv || 'MEMORY_BRAIN_TOKEN'
14
+ const token = cfg.token || (typeof process !== 'undefined' && process.env ? process.env[tokenEnv] : '') || ''
15
+ const baseUrl = (cfg.baseUrl || (typeof process !== 'undefined' && process.env ? process.env.MEMORY_BRAIN_URL : '') || 'http://127.0.0.1:28080').replace(/\/+$/, '')
16
+ return {
17
+ enabled: cfg.enabled !== false,
18
+ baseUrl,
19
+ token,
20
+ tokenEnv,
21
+ autoInject: cfg.autoInject !== false,
22
+ budget: Number(cfg.budget) || 2000,
23
+ timeoutMs: Number(cfg.timeoutMs) || 3500,
24
+ }
25
+ }
26
+
27
+ export function parseMemoryListText(text) {
28
+ if (!text || typeof text !== 'string') return []
29
+ const items = []
30
+ for (const line of text.split('\n')) {
31
+ const trimmed = line.trim()
32
+ const idMatch = trimmed.match(/\[id:([0-9a-fA-F-]+)\]/)
33
+ if (!idMatch) continue
34
+ const id = idMatch[1]
35
+ let content = trimmed
36
+ const dashIdx = trimmed.indexOf('—')
37
+ if (dashIdx !== -1) {
38
+ content = trimmed.slice(dashIdx + 1).trim()
39
+ } else {
40
+ content = trimmed.replace(/^-?\s*\[id:[^\]]+\]\s*/, '').trim()
41
+ }
42
+ items.push({ id, content, raw: trimmed })
43
+ }
44
+ return items
45
+ }
46
+
47
+ export function cleanRecalledMemories(text) {
48
+ if (!text || typeof text !== 'string') return ''
49
+ const lines = text.split('\n')
50
+ const out = []
51
+ for (const line of lines) {
52
+ const trimmed = line.trim()
53
+ if (!trimmed) continue
54
+ if (trimmed.startsWith('[protocol') || trimmed.startsWith('Index not fully ready')) continue
55
+ const idMatch = trimmed.match(/\[id:([0-9a-fA-F-]+)\]\s*(.*?)(?:\s+—\s+written by.*)?$/)
56
+ if (idMatch) {
57
+ const fact = idMatch[2].replace(/\s+—\s+written by.*$/, '').trim()
58
+ if (fact) out.push(`- ${fact}`)
59
+ } else if (trimmed.startsWith('- ')) {
60
+ out.push(trimmed)
61
+ }
62
+ }
63
+ return out.join('\n')
64
+ }
65
+
66
+ export function formatMemoryContext(recalledText, userId) {
67
+ const clean = cleanRecalledMemories(recalledText)
68
+ if (!clean) return ''
69
+ return `[User Memory Profile (userId: ${userId})]:\n${clean}`
70
+ }
71
+
72
+ export function extractConversationalPreferences(text) {
73
+ if (!text || typeof text !== 'string') return null
74
+ const s = text.trim()
75
+ if (s.startsWith('/')) return null
76
+ const patterns = [
77
+ /^(?:СаĐŋĐžĐŧĐŊи|ŅĐžŅ…Ņ€Đ°ĐŊи в ĐŋаĐŧŅŅ‚ŅŒ)(?:\s*[:,]\s*|\s+)(.+)$/i,
78
+ /^(?:remember|note that)(?:\s*[:,]\s*|\s+)(.+)$/i,
79
+ /(?:Ņ ĐŋŅ€ĐĩĐ´ĐŋĐžŅ‡Đ¸Ņ‚Đ°ŅŽ|ĐŧĐžĐĩ ĐŋŅ€ĐĩĐ´ĐŋĐžŅ‡Ņ‚ĐĩĐŊиĐĩ|ĐŧОК Đ˛Ņ‹ĐąĐžŅ€)\s+(.+)/i,
80
+ /(?:i prefer|my preference is)\s+(.+)/i,
81
+ /(?:Đ˛ŅĐĩĐŗĐ´Đ° ĐžŅ‚Đ˛ĐĩŅ‡Đ°Đš|Đ˛ŅĐĩĐŗĐ´Đ° ĐŋĐ¸ŅˆĐ¸|Đ˛ŅĐĩĐŗĐ´Đ° Đ¸ŅĐŋĐžĐģŅŒĐˇŅƒĐš)\s+(.+)/i,
82
+ /(?:always answer|always reply|always use)\s+(.+)/i,
83
+ /(?:ĐŧĐĩĐŊŅ ĐˇĐžĐ˛ŅƒŅ‚|ĐŧĐžĐĩ иĐŧŅ)\s+([A-Za-zА-Đ¯Đ°-ŅĐŅ‘0-9_-]+)/i,
84
+ /(?:my name is|call me)\s+([A-Za-z0-9_-]+)/i,
85
+ ]
86
+ for (const pat of patterns) {
87
+ const m = s.match(pat)
88
+ if (m && m[1]) return m[1].trim()
89
+ }
90
+ return null
91
+ }
92
+
93
+ export async function callMemoryMcp(rawConfig, toolName, args, signal) {
94
+ const cfg = resolveMemoryConfig(rawConfig)
95
+ if (!cfg.enabled) {
96
+ return { ok: false, error: 'memory_disabled' }
97
+ }
98
+
99
+ const controller = new AbortController()
100
+ const timeoutId = setTimeout(() => controller.abort(), cfg.timeoutMs)
101
+ let onAbort = null
102
+ if (signal) {
103
+ onAbort = () => controller.abort()
104
+ signal.addEventListener('abort', onAbort, { once: true })
105
+ }
106
+
107
+ try {
108
+ const headers = {
109
+ 'Content-Type': 'application/json',
110
+ Accept: 'application/json, text/event-stream',
111
+ }
112
+ if (cfg.token) {
113
+ headers.Authorization = `Bearer ${cfg.token}`
114
+ }
115
+
116
+ const res = await fetch(`${cfg.baseUrl}/mcp`, {
117
+ method: 'POST',
118
+ headers,
119
+ body: JSON.stringify({
120
+ jsonrpc: '2.0',
121
+ id: `msgw-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
122
+ method: 'tools/call',
123
+ params: {
124
+ name: toolName,
125
+ arguments: args || {},
126
+ },
127
+ }),
128
+ signal: controller.signal,
129
+ })
130
+
131
+ if (!res.ok) {
132
+ return { ok: false, error: `HTTP ${res.status}` }
133
+ }
134
+
135
+ const data = await res.json()
136
+ if (data?.error) {
137
+ return { ok: false, error: data.error.message || `error code ${data.error.code}` }
138
+ }
139
+
140
+ const text = data?.result?.content?.[0]?.text
141
+ return { ok: true, text: typeof text === 'string' ? text : JSON.stringify(data?.result ?? {}) }
142
+ } catch (err) {
143
+ return { ok: false, error: err?.message || String(err) }
144
+ } finally {
145
+ clearTimeout(timeoutId)
146
+ if (signal && onAbort) {
147
+ signal.removeEventListener('abort', onAbort)
148
+ }
149
+ }
150
+ }
151
+
152
+ export async function listUserMemories({ config, userId, limit = 20, signal }) {
153
+ if (!userId) return { ok: false, error: 'missing_user_id', items: [] }
154
+ const scope = `user:${userId}`
155
+ const res = await callMemoryMcp(config, 'brain_list', { scope, limit }, signal)
156
+ if (!res.ok) {
157
+ return { ok: false, error: res.error, items: [] }
158
+ }
159
+ const items = parseMemoryListText(res.text)
160
+ return { ok: true, items, raw: res.text }
161
+ }
162
+
163
+ export async function recallUserMemories({ config, userId, query = '', budget, signal }) {
164
+ if (!userId) return ''
165
+ const scope = `user:${userId}`
166
+ const cleanQ = String(query || '').trim()
167
+
168
+ // If query is trivial or empty, recall user profile by listing memories
169
+ if (!cleanQ || cleanQ.length < 3) {
170
+ const listRes = await listUserMemories({ config, userId, limit: 10, signal })
171
+ if (!listRes.ok || !listRes.items.length) return ''
172
+ const facts = listRes.items.map((it) => `- ${it.content}`).join('\n')
173
+ return formatMemoryContext(facts, userId)
174
+ }
175
+
176
+ const res = await callMemoryMcp(config, 'brain_recall', {
177
+ query: cleanQ,
178
+ scope,
179
+ limit: 10,
180
+ budget: budget || 2000,
181
+ }, signal)
182
+
183
+ if (!res.ok || !res.text) return ''
184
+ return formatMemoryContext(res.text, userId)
185
+ }
186
+
187
+ export async function rememberUserFact({ config, userId, content, category = 'preference', signal }) {
188
+ if (!userId) return { ok: false, error: 'missing_user_id' }
189
+ const text = String(content || '').trim()
190
+ if (!text) return { ok: false, error: 'empty_content' }
191
+ const scope = `user:${userId}`
192
+
193
+ const res = await callMemoryMcp(config, 'brain_remember', {
194
+ content: text,
195
+ scope,
196
+ category,
197
+ permanent: true,
198
+ }, signal)
199
+
200
+ if (!res.ok) return res
201
+
202
+ // Try extracting memoryId from json response if present
203
+ let memoryId = null
204
+ try {
205
+ const parsed = JSON.parse(res.text)
206
+ memoryId = parsed.memoryId || parsed.id || parsed.memoryIds?.[0] || null
207
+ } catch {
208
+ /* raw string response is fine */
209
+ }
210
+
211
+ return { ok: true, memoryId, text: res.text }
212
+ }
213
+
214
+ export async function forgetUserMemory({ config, userId, memoryId, signal }) {
215
+ if (!userId) return { ok: false, error: 'missing_user_id' }
216
+ const target = String(memoryId || '').trim()
217
+ if (!target) return { ok: false, error: 'missing_memory_id' }
218
+
219
+ if (target.toLowerCase() === 'all') {
220
+ const listRes = await listUserMemories({ config, userId, limit: 100, signal })
221
+ if (!listRes.ok) return listRes
222
+ let forgotten = 0
223
+ for (const item of listRes.items) {
224
+ const delRes = await callMemoryMcp(config, 'brain_forget', {
225
+ memory_id: item.id,
226
+ confirm: true,
227
+ }, signal)
228
+ if (delRes.ok) forgotten++
229
+ }
230
+ return { ok: true, count: forgotten }
231
+ }
232
+
233
+ // Support short prefix matches (e.g. 8 chars)
234
+ let resolvedId = target
235
+ if (target.length < 36) {
236
+ const listRes = await listUserMemories({ config, userId, limit: 50, signal })
237
+ if (listRes.ok && listRes.items) {
238
+ const match = listRes.items.find((it) => it.id.toLowerCase().startsWith(target.toLowerCase()))
239
+ if (match) resolvedId = match.id
240
+ }
241
+ }
242
+
243
+ const res = await callMemoryMcp(config, 'brain_forget', {
244
+ memory_id: resolvedId,
245
+ confirm: true,
246
+ }, signal)
247
+
248
+ return res
249
+ }
250
+
251
+ export async function recordTurnMemory({ config, userId, userText, assistantText, signal, logger }) {
252
+ const extracted = extractConversationalPreferences(userText)
253
+ if (!extracted) return { ok: true, skipped: true }
254
+
255
+ try {
256
+ const res = await rememberUserFact({
257
+ config,
258
+ userId,
259
+ content: extracted,
260
+ category: 'preference',
261
+ signal,
262
+ })
263
+ if (res.ok && logger) {
264
+ logger.debug?.(`[memory-brain] auto-recorded user preference: "${extracted}" for user ${userId}`)
265
+ }
266
+ return res
267
+ } catch (err) {
268
+ if (logger) {
269
+ logger.debug?.(`[memory-brain] recordTurnMemory failed: ${err?.message || err}`)
270
+ }
271
+ return { ok: false, error: err?.message || String(err) }
272
+ }
273
+ }
package/lib/workspace.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { resolve, normalize, basename } from 'node:path'
2
2
  import { statSync, realpathSync, existsSync } from 'node:fs'
3
3
  import { readFile } from 'node:fs/promises'
4
+ import { readFileSync } from 'node:fs'
4
5
  import { randomUUID } from 'node:crypto'
5
6
  import os from 'node:os'
6
7
  import path from 'node:path'
@@ -146,4 +147,114 @@ export async function registerSessionInWorkspace(ctx, sessionId, cwd, logger) {
146
147
  }
147
148
 
148
149
  return false
149
- }
150
+ }
151
+ import { writeJsonAtomicSync } from "./storage-atomic.js"
152
+
153
+ export function resolveTopicWorkspacesStoragePath(config = {}) {
154
+ if (config.topicWorkspacesStoragePath) return config.topicWorkspacesStoragePath
155
+ const dshHome = process.env.DSH_HOME || path.join(os.homedir(), ".dsh")
156
+ return path.join(dshHome, "storages", "topic-workspaces.json")
157
+ }
158
+
159
+ export function inspectGitWorkspace(dirPath) {
160
+ try {
161
+ const gitPath = path.join(dirPath, ".git")
162
+ if (existsSync(gitPath)) {
163
+ const st = statSync(gitPath)
164
+ if (st.isDirectory()) {
165
+ return { isGit: true, isWorktree: false }
166
+ }
167
+ if (st.isFile()) {
168
+ const content = readFileSync(gitPath, "utf8")
169
+ const match = content.match(/gitdir:\s*(.+)/i)
170
+ return { isGit: true, isWorktree: true, gitdir: match ? match[1].trim() : null }
171
+ }
172
+ }
173
+ } catch {
174
+ // not a git repo
175
+ }
176
+ return { isGit: false, isWorktree: false }
177
+ }
178
+
179
+ export function createTopicWorkspaceStore(filePath, { logger } = {}) {
180
+ let cache = { workspaces: {} }
181
+ try {
182
+ if (existsSync(filePath)) {
183
+ const raw = JSON.parse(readFileSync(filePath, "utf8"))
184
+ if (raw && typeof raw === "object" && raw.workspaces) {
185
+ cache = raw
186
+ } else if (raw && typeof raw === "object") {
187
+ cache = { workspaces: raw }
188
+ }
189
+ }
190
+ } catch (err) {
191
+ if (err?.code !== "ENOENT") {
192
+ logger?.warn?.(`[dsh-messenger-gateway] topic-workspaces load error: ${err?.message || err}`)
193
+ }
194
+ }
195
+
196
+ function save() {
197
+ try {
198
+ writeJsonAtomicSync(filePath, cache)
199
+ } catch (err) {
200
+ logger?.warn?.(`[dsh-messenger-gateway] topic-workspaces save error: ${err?.message || err}`)
201
+ }
202
+ }
203
+
204
+ function makeKey(chatId, threadId = 0) {
205
+ const tid = Number(threadId) || 0
206
+ return tid > 0 ? `${chatId}:${tid}` : String(chatId)
207
+ }
208
+
209
+ return {
210
+ get(chatId, threadId = 0) {
211
+ if (chatId === undefined || chatId === null) return null
212
+ const key = makeKey(chatId, threadId)
213
+ if (cache.workspaces[key]) return { ...cache.workspaces[key] }
214
+ if (threadId) {
215
+ const baseKey = String(chatId)
216
+ if (cache.workspaces[baseKey]) return { ...cache.workspaces[baseKey] }
217
+ }
218
+ return null
219
+ },
220
+ set(chatId, threadId = 0, binding = {}) {
221
+ if (chatId === undefined || chatId === null) return
222
+ const key = makeKey(chatId, threadId)
223
+ cache.workspaces[key] = {
224
+ path: binding.path,
225
+ name: binding.name || basename(binding.path),
226
+ role: binding.role || null,
227
+ worktree: Boolean(binding.worktree),
228
+ boundAt: binding.boundAt || new Date().toISOString(),
229
+ }
230
+ save()
231
+ },
232
+ delete(chatId, threadId = 0) {
233
+ if (chatId === undefined || chatId === null) return false
234
+ const key = makeKey(chatId, threadId)
235
+ if (cache.workspaces[key]) {
236
+ delete cache.workspaces[key]
237
+ save()
238
+ return true
239
+ }
240
+ return false
241
+ },
242
+ list(chatId) {
243
+ if (chatId === undefined || chatId === null) return []
244
+ const prefix = `${chatId}:`
245
+ const baseKey = String(chatId)
246
+ const results = []
247
+ for (const [key, val] of Object.entries(cache.workspaces)) {
248
+ if (key === baseKey || key.startsWith(prefix)) {
249
+ const parts = key.split(":")
250
+ const tid = parts[1] ? Number(parts[1]) : 0
251
+ results.push({ threadId: tid, ...val })
252
+ }
253
+ }
254
+ return results
255
+ },
256
+ all() {
257
+ return { ...cache.workspaces }
258
+ },
259
+ }
260
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-messenger-gateway",
3
- "version": "0.4.25",
3
+ "version": "0.4.26",
4
4
  "description": "Telegram messenger bridge for DeepSeek Harness: sessions, steer, homes, inline asks, notify bridge, and optional TTS voice notes.",
5
5
  "license": "MIT",
6
6
  "type": "module",