@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.
- package/lib/adapters/index.js +1 -0
- package/lib/adapters/telegram-inbound.js +1 -1
- package/lib/adapters/telegram.js +138 -0
- package/lib/artifacts.js +353 -23
- package/lib/commands.js +6 -0
- package/lib/config.js +10 -0
- package/lib/documents.js +167 -3
- package/lib/gateway-commands.js +157 -6
- package/lib/gateway-turn.js +29 -3
- package/lib/gateway.js +22 -2
- package/lib/memory-brain.js +273 -0
- package/lib/workspace.js +112 -1
- package/package.json +1 -1
package/lib/documents.js
CHANGED
|
@@ -14,7 +14,11 @@ export function formatInboundDocument(att, parsed = null) {
|
|
|
14
14
|
|
|
15
15
|
if (parsed?.text) {
|
|
16
16
|
const truncNote = parsed.truncated ? ' (content truncated)' : ''
|
|
17
|
-
|
|
17
|
+
if (parsed.type === 'zip') {
|
|
18
|
+
base += `\n\n[Extracted archive structure and code${truncNote}]:\n\`\`\`\n${parsed.text}\n\`\`\``
|
|
19
|
+
} else {
|
|
20
|
+
base += `\n\n[Extracted text from file${truncNote}]:\n\`\`\`\n${parsed.text}\n\`\`\``
|
|
21
|
+
}
|
|
18
22
|
}
|
|
19
23
|
return base
|
|
20
24
|
}
|
|
@@ -127,6 +131,160 @@ export function extractDocxText(buffer) {
|
|
|
127
131
|
return ''
|
|
128
132
|
}
|
|
129
133
|
|
|
134
|
+
|
|
135
|
+
const IGNORED_ZIP_DIRS = new Set([
|
|
136
|
+
"node_modules", ".git", ".turbo", "dist", "build", "vendor", "__pycache__", ".venv", ".idea", ".vscode",
|
|
137
|
+
])
|
|
138
|
+
|
|
139
|
+
const IGNORED_ZIP_FILES = new Set([
|
|
140
|
+
"package-lock.json", "pnpm-lock.yaml", "yarn.lock", "cargo.lock", "gemfile.lock", "poetry.lock",
|
|
141
|
+
])
|
|
142
|
+
|
|
143
|
+
const BINARY_ZIP_EXTS = new Set([
|
|
144
|
+
".png", ".jpg", ".jpeg", ".gif", ".ico", ".webp", ".pdf", ".mp3", ".mp4", ".zip", ".tar", ".gz", ".7z", ".rar",
|
|
145
|
+
".exe", ".dll", ".so", ".dylib", ".class", ".pyc", ".o", ".a", ".woff", ".woff2", ".ttf", ".eot",
|
|
146
|
+
])
|
|
147
|
+
|
|
148
|
+
export function isSafeZipPath(name) {
|
|
149
|
+
if (!name || typeof name !== "string") return false
|
|
150
|
+
const normalized = name.replace(/\\/g, "/")
|
|
151
|
+
if (normalized.startsWith("/") || /^[a-zA-Z]:/.test(normalized)) return false
|
|
152
|
+
const parts = normalized.split("/")
|
|
153
|
+
if (parts.includes("..") || parts.includes(".")) return false
|
|
154
|
+
return true
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function extractZipEntries(buffer, opts = {}) {
|
|
158
|
+
const {
|
|
159
|
+
maxEntries = 100,
|
|
160
|
+
maxUncompressedBytes = 10 * 1024 * 1024,
|
|
161
|
+
maxFileBytes = 512 * 1024,
|
|
162
|
+
} = opts
|
|
163
|
+
|
|
164
|
+
// Locate End of Central Directory Record (EOCD: 0x06054b50)
|
|
165
|
+
let eocdOffset = -1
|
|
166
|
+
for (let i = buffer.length - 22; i >= Math.max(0, buffer.length - 65557); i--) {
|
|
167
|
+
if (buffer[i] === 0x50 && buffer[i + 1] === 0x4b && buffer[i + 2] === 0x05 && buffer[i + 3] === 0x06) {
|
|
168
|
+
eocdOffset = i
|
|
169
|
+
break
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (eocdOffset === -1) {
|
|
173
|
+
throw new Error("Invalid zip: End of Central Directory signature not found")
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const totalEntries = buffer.readUInt16LE(eocdOffset + 10)
|
|
177
|
+
const cdOffset = buffer.readUInt32LE(eocdOffset + 16)
|
|
178
|
+
|
|
179
|
+
const entries = []
|
|
180
|
+
let pos = cdOffset
|
|
181
|
+
let totalUncompressed = 0
|
|
182
|
+
|
|
183
|
+
for (let idx = 0; idx < totalEntries && idx < maxEntries; idx++) {
|
|
184
|
+
if (pos + 46 > buffer.length) break
|
|
185
|
+
if (buffer.readUInt32LE(pos) !== 0x02014b50) break
|
|
186
|
+
|
|
187
|
+
const compMethod = buffer.readUInt16LE(pos + 10)
|
|
188
|
+
const compSize = buffer.readUInt32LE(pos + 20)
|
|
189
|
+
const uncompSize = buffer.readUInt32LE(pos + 24)
|
|
190
|
+
const nameLen = buffer.readUInt16LE(pos + 28)
|
|
191
|
+
const extraLen = buffer.readUInt16LE(pos + 30)
|
|
192
|
+
const commentLen = buffer.readUInt16LE(pos + 32)
|
|
193
|
+
const localOffset = buffer.readUInt32LE(pos + 42)
|
|
194
|
+
|
|
195
|
+
if (pos + 46 + nameLen > buffer.length) break
|
|
196
|
+
const rawName = buffer.toString("utf8", pos + 46, pos + 46 + nameLen).replace(/\\/g, "/")
|
|
197
|
+
pos += 46 + nameLen + extraLen + commentLen
|
|
198
|
+
|
|
199
|
+
if (rawName.endsWith("/")) continue
|
|
200
|
+
if (!isSafeZipPath(rawName)) continue
|
|
201
|
+
|
|
202
|
+
totalUncompressed += uncompSize
|
|
203
|
+
if (totalUncompressed > maxUncompressedBytes) {
|
|
204
|
+
break
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const parts = rawName.split("/")
|
|
208
|
+
if (parts.some((p) => IGNORED_ZIP_DIRS.has(p.toLowerCase()))) continue
|
|
209
|
+
const base = parts[parts.length - 1].toLowerCase()
|
|
210
|
+
if (IGNORED_ZIP_FILES.has(base)) continue
|
|
211
|
+
const ext = extname(base).toLowerCase()
|
|
212
|
+
if (BINARY_ZIP_EXTS.has(ext)) continue
|
|
213
|
+
|
|
214
|
+
if (localOffset + 30 > buffer.length) continue
|
|
215
|
+
if (buffer.readUInt32LE(localOffset) !== 0x04034b50) continue
|
|
216
|
+
const localNameLen = buffer.readUInt16LE(localOffset + 26)
|
|
217
|
+
const localExtraLen = buffer.readUInt16LE(localOffset + 28)
|
|
218
|
+
const dataStart = localOffset + 30 + localNameLen + localExtraLen
|
|
219
|
+
|
|
220
|
+
if (dataStart + compSize > buffer.length) continue
|
|
221
|
+
const compData = buffer.subarray(dataStart, dataStart + compSize)
|
|
222
|
+
|
|
223
|
+
let content = null
|
|
224
|
+
const canExtract = uncompSize <= maxFileBytes && (TEXT_INJECT_EXTS.has(ext) || !ext)
|
|
225
|
+
if (canExtract) {
|
|
226
|
+
try {
|
|
227
|
+
if (compMethod === 8) {
|
|
228
|
+
content = inflateRawSync(compData).toString("utf8")
|
|
229
|
+
} else if (compMethod === 0) {
|
|
230
|
+
content = compData.toString("utf8")
|
|
231
|
+
}
|
|
232
|
+
} catch {
|
|
233
|
+
content = null
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
entries.push({
|
|
238
|
+
name: rawName,
|
|
239
|
+
size: uncompSize,
|
|
240
|
+
ext,
|
|
241
|
+
content,
|
|
242
|
+
})
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return { entries, totalInArchive: totalEntries, totalUncompressed }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export function formatZipSummary(extracted, maxBytes = 64 * 1024) {
|
|
249
|
+
const { entries, totalInArchive } = extracted
|
|
250
|
+
if (!entries.length) {
|
|
251
|
+
return {
|
|
252
|
+
text: `[Archive contains no readable code or text files (${totalInArchive} entries total)]`,
|
|
253
|
+
fileCount: 0,
|
|
254
|
+
truncated: false,
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
let summary = `Archive structure (${entries.length} text files extracted, ${totalInArchive} total entries):\n`
|
|
259
|
+
for (const entry of entries) {
|
|
260
|
+
summary += ` - ${entry.name} (${entry.size} B)\n`
|
|
261
|
+
}
|
|
262
|
+
summary += "\n"
|
|
263
|
+
|
|
264
|
+
let truncated = false
|
|
265
|
+
for (const entry of entries) {
|
|
266
|
+
if (!entry.content) continue
|
|
267
|
+
const header = `--- File: ${entry.name} ---\n`
|
|
268
|
+
const fileBlock = header + entry.content.trim() + "\n\n"
|
|
269
|
+
if (summary.length + fileBlock.length > maxBytes) {
|
|
270
|
+
const remaining = maxBytes - summary.length - header.length - 40
|
|
271
|
+
if (remaining > 100) {
|
|
272
|
+
summary += header + entry.content.slice(0, remaining).trim() + "\n... [File content truncated]\n\n"
|
|
273
|
+
}
|
|
274
|
+
summary += `[Archive ingestion truncated: remaining ${entries.length} files omitted to fit context]\n`
|
|
275
|
+
truncated = true
|
|
276
|
+
break
|
|
277
|
+
}
|
|
278
|
+
summary += fileBlock
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
return {
|
|
282
|
+
text: summary.trim(),
|
|
283
|
+
fileCount: entries.length,
|
|
284
|
+
truncated,
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
130
288
|
export async function parseDocument(filePath, opts = {}) {
|
|
131
289
|
const { maxBytes = 64 * 1024 } = opts
|
|
132
290
|
const ext = extname(filePath).toLowerCase()
|
|
@@ -147,7 +305,7 @@ export async function parseDocument(filePath, opts = {}) {
|
|
|
147
305
|
const { bytesRead } = await handle.read(buf, 0, toRead, 0)
|
|
148
306
|
rawBuffer = buf.subarray(0, bytesRead)
|
|
149
307
|
truncated = st.size > toRead
|
|
150
|
-
} else if (ext === '.pdf' || ext === '.docx') {
|
|
308
|
+
} else if (ext === '.pdf' || ext === '.docx' || ext === '.zip') {
|
|
151
309
|
const maxBinary = Math.max(maxBytes * 4, 10 * 1024 * 1024)
|
|
152
310
|
if (st.size > maxBinary) {
|
|
153
311
|
return { parsed: false, error: `File size (${st.size} bytes) exceeds safety parse limit` }
|
|
@@ -165,7 +323,13 @@ export async function parseDocument(filePath, opts = {}) {
|
|
|
165
323
|
let text = ''
|
|
166
324
|
let parsedType = 'text'
|
|
167
325
|
|
|
168
|
-
if (ext === '.
|
|
326
|
+
if (ext === '.zip') {
|
|
327
|
+
parsedType = 'zip'
|
|
328
|
+
const extracted = extractZipEntries(rawBuffer, opts)
|
|
329
|
+
const formatted = formatZipSummary(extracted, maxBytes)
|
|
330
|
+
text = formatted.text
|
|
331
|
+
truncated = formatted.truncated
|
|
332
|
+
} else if (ext === '.pdf') {
|
|
169
333
|
parsedType = 'pdf'
|
|
170
334
|
text = extractPdfText(rawBuffer)
|
|
171
335
|
} else if (ext === '.docx') {
|
package/lib/gateway-commands.js
CHANGED
|
@@ -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 <path> [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 <path> [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 <fact></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 <fact></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 <fact></code>',
|
|
378
|
+
'β’ Forget fact: <code>/forget <id></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 <id|all></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 (
|
|
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)
|
package/lib/gateway-turn.js
CHANGED
|
@@ -5,7 +5,7 @@ import { getPersona } from './personas.js'
|
|
|
5
5
|
import { MESSENGER_RELAY_INSTRUCTION, stripReasoningPreamble, splitText } from './text.js'
|
|
6
6
|
import { formatInboundDocument, documentOnlyHint, parseDocument } from './documents.js'
|
|
7
7
|
import { t } from './locales/index.js'
|
|
8
|
-
import { processDiagramsAndTables } from './artifacts.js'
|
|
8
|
+
import { processDiagramsAndTables, processDiagramsAndTablesAsync } from './artifacts.js'
|
|
9
9
|
import { prepareTtsText, toTelegramVoiceFile } from './tts.js'
|
|
10
10
|
import { shouldSpeakReply } from './voice-prefs.js'
|
|
11
11
|
import { speakText, transcribeVoice } from './integrations.js'
|
|
@@ -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) {
|
|
@@ -289,7 +304,7 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
289
304
|
const thoughtHeader = String(gw.resolveLocale(input)).toLowerCase().startsWith('zh') ? 'π§ <i>ζθθΏη¨:</i>' : 'π§ <i>Thought process:</i>'
|
|
290
305
|
rawAnswer = `${quoteTag}${thoughtHeader}\n${escapeHtml(parsedReasoning.thought)}</blockquote>\n\n${cleanContent}`
|
|
291
306
|
}
|
|
292
|
-
const processed =
|
|
307
|
+
const processed = await processDiagramsAndTablesAsync(rawAnswer, {
|
|
293
308
|
artifactPreviews: gw.tg().artifactPreviews !== false,
|
|
294
309
|
})
|
|
295
310
|
const answer = processed.text
|
|
@@ -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 =
|
|
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()}`)
|