@goodandready/dsh-messenger-gateway 0.4.24 → 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.
@@ -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.24",
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",