@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.
@@ -27,6 +27,7 @@ export default function createAdapters(deps) {
27
27
  apiRoot: tg.apiRoot,
28
28
  quickActions: tg.quickActions !== false,
29
29
  artifactPreviews: tg.artifactPreviews !== false,
30
+ mediaGroupDebounceMs: tg.mediaGroupDebounceMs,
30
31
  media: config.media,
31
32
  onMessage,
32
33
  onCallback,
@@ -3,7 +3,7 @@ import {
3
3
  IMAGE_EXT_TO_MIME, VIDEO_EXT_TO_MIME, classifyDocument,
4
4
  extOf, TELEGRAM_MAX_DOC_BYTES,
5
5
  } from '../media.js'
6
- import { TEXT_INJECT_EXTS } from '../documents.js'
6
+ import { TEXT_INJECT_EXTS, parseDocument } from '../documents.js'
7
7
 
8
8
  export async function extractTelegramInboundMedia(adapter, msg, initialText, maxDocBytes = TELEGRAM_MAX_DOC_BYTES, maxTextInjectBytes = 100 * 1024) {
9
9
  let text = initialText || ''
@@ -67,6 +67,8 @@ export class TelegramAdapter {
67
67
  this.webhookSecret = String(opts.webhookSecret || '').trim()
68
68
  this.offset = 0
69
69
  this.stopped = false
70
+ this.mediaGroups = new Map()
71
+ this.mediaGroupDebounceMs = Number(opts.mediaGroupDebounceMs) || 650
70
72
  this.pollTimer = undefined
71
73
  this.botId = 0
72
74
  this.botUsername = ''
@@ -235,6 +237,12 @@ export class TelegramAdapter {
235
237
 
236
238
  stop() {
237
239
  this.stopped = true
240
+ if (this.mediaGroups) {
241
+ for (const group of this.mediaGroups.values()) {
242
+ if (group.timeout) clearTimeout(group.timeout)
243
+ }
244
+ this.mediaGroups.clear()
245
+ }
238
246
  if (this.pollTimer) clearTimeout(this.pollTimer)
239
247
  if (this.statusIndicator) this.setStatusIndicator(this.statusOffline).catch((err) => {
240
248
  this.logger?.debug?.('telegram setStatusIndicator offline failed:', err?.message || err)
@@ -302,6 +310,12 @@ export class TelegramAdapter {
302
310
  }
303
311
  const msg = update.message
304
312
  if (!msg) return
313
+
314
+ if (msg.media_group_id) {
315
+ this.bufferMediaGroup(msg)
316
+ return
317
+ }
318
+
305
319
  try { await this.handleMessage(msg) } catch (e) {
306
320
  this.logger?.warn?.(`message: ${e.message}`)
307
321
  }
@@ -367,6 +381,130 @@ export class TelegramAdapter {
367
381
  }
368
382
  }
369
383
 
384
+ bufferMediaGroup(msg) {
385
+ const key = `${msg.chat.id}:${msg.media_group_id}`
386
+ let group = this.mediaGroups.get(key)
387
+ if (!group) {
388
+ group = {
389
+ messages: [],
390
+ timeout: null,
391
+ }
392
+ this.mediaGroups.set(key, group)
393
+ }
394
+ if (group.timeout) {
395
+ clearTimeout(group.timeout)
396
+ }
397
+ group.messages.push(msg)
398
+ group.timeout = setTimeout(() => {
399
+ this.flushMediaGroup(key).catch((e) => {
400
+ this.logger?.warn?.(`flushMediaGroup failed: ${e.message}`)
401
+ })
402
+ }, this.mediaGroupDebounceMs)
403
+ group.timeout.unref?.()
404
+ }
405
+
406
+ async flushMediaGroup(key) {
407
+ const group = this.mediaGroups.get(key)
408
+ if (!group) return
409
+ this.mediaGroups.delete(key)
410
+ if (group.timeout) {
411
+ clearTimeout(group.timeout)
412
+ group.timeout = null
413
+ }
414
+ const messages = group.messages || []
415
+ if (!messages.length) return
416
+
417
+ await this.handleMediaGroup(messages)
418
+ }
419
+
420
+ async handleMediaGroup(messages) {
421
+ if (!messages.length) return
422
+ const primaryMsg = messages.find((m) => m.text || m.caption) || messages[messages.length - 1]
423
+ const chatId = primaryMsg.chat.id
424
+ const chatType = primaryMsg.chat?.type || 'private'
425
+ const userId = primaryMsg.from?.id ?? chatId
426
+
427
+ const textPieces = []
428
+ for (const m of messages) {
429
+ const t = m.text ?? m.caption
430
+ if (t && !textPieces.includes(t)) textPieces.push(t)
431
+ }
432
+ let text = textPieces.join('\n\n')
433
+ const entities = messages.flatMap((m) => m.entities || m.caption_entities || [])
434
+
435
+ const gate = shouldProcessTelegramMessage({
436
+ chatType,
437
+ text,
438
+ entities,
439
+ replyTo: primaryMsg.reply_to_message,
440
+ botId: this.botId,
441
+ botUsername: this.botUsername,
442
+ groupsEnabled: this.groupsEnabled,
443
+ requireMention: this.groupRequireMention,
444
+ })
445
+ if (!gate.ok) return
446
+
447
+ if (!this.allowed(userId)) {
448
+ if (chatType !== 'private') return
449
+ if (this.onUnauthorized) {
450
+ await this.onUnauthorized({
451
+ platform: 'telegram', chatId, userId, threadId: primaryMsg.message_thread_id || 0,
452
+ username: primaryMsg.from?.username || '',
453
+ reply: async (payload) => this.sendReply(chatId, primaryMsg.message_id, payload, primaryMsg.message_thread_id || 0),
454
+ })
455
+ }
456
+ return
457
+ }
458
+
459
+ text = stripBotCommandSuffix(text, this.botUsername)
460
+ const threadId = primaryMsg.message_thread_id || 0
461
+ const maxDocBytes = this.media.maxDocBytes ?? TELEGRAM_MAX_DOC_BYTES
462
+ const maxTextInjectBytes = this.media.maxTextInjectBytes ?? 100 * 1024
463
+ const replyMsg = primaryMsg.reply_to_message
464
+ let replyText = ''
465
+ if (replyMsg) {
466
+ const quoted = replyMsg.text ?? replyMsg.caption ?? ''
467
+ const quoteFrag = primaryMsg.quote?.text || ''
468
+ replyText = quoteFrag
469
+ ? `${quoted}${quoted ? '\n' : ''}[quote: ${quoteFrag}]`
470
+ : quoted
471
+ }
472
+
473
+ const allAttachments = []
474
+ const docTextPieces = []
475
+ for (const m of messages) {
476
+ const inbound = await extractTelegramInboundMedia(this, m, '', maxDocBytes, maxTextInjectBytes)
477
+ if (inbound.attachments?.length) {
478
+ allAttachments.push(...inbound.attachments)
479
+ }
480
+ if (inbound.text) {
481
+ docTextPieces.push(inbound.text)
482
+ }
483
+ }
484
+ if (docTextPieces.length) {
485
+ text = text ? `${text}\n\n${docTextPieces.join('\n\n')}` : docTextPieces.join('\n\n')
486
+ }
487
+
488
+ const messageId = primaryMsg.message_id
489
+ const reply = async (payload) => this.sendReply(chatId, messageId, payload, threadId)
490
+ const typing = async () => {
491
+ try {
492
+ await this.call('sendChatAction', { chat_id: chatId, action: 'typing', ...telegramThreadParams(threadId) })
493
+ } catch (err) {
494
+ this.logger?.debug?.('telegram sendChatAction typing failed:', err?.message || err)
495
+ }
496
+ }
497
+ const startStream = async () => this.startStreamMessage(chatId, messageId, threadId)
498
+ const startProgress = async () => this.startProgressMessage(chatId, messageId, threadId)
499
+ const react = async (emoji) => this.setReaction(chatId, messageId, emoji)
500
+
501
+ await this.onMessage({
502
+ platform: 'telegram', chatId, userId, threadId, chatType, text,
503
+ attachments: allAttachments, replyText,
504
+ messageId, reply, typing, startStream, startProgress, react,
505
+ })
506
+ }
507
+
370
508
  async handleMessage(msg) {
371
509
  const chatId = msg.chat.id
372
510
  const chatType = msg.chat?.type || 'private'
package/lib/artifacts.js CHANGED
@@ -1,6 +1,12 @@
1
+ import { createHash } from "node:crypto"
2
+ import { spawn } from "node:child_process"
3
+ import { writeFileSync, readFileSync, unlinkSync } from "node:fs"
4
+ import { tmpdir } from "node:os"
5
+ import { join } from "node:path"
6
+
1
7
  export function extractMermaidDiagrams(text) {
2
- if (!text || typeof text !== 'string') return []
3
- const regex = /```mermaid\s*\n([\s\S]*?)```/gi
8
+ if (!text || typeof text !== "string") return []
9
+ const regex = /```(?:mermaid|chart)\s*\n([\s\S]*?)```/gi
4
10
  const diagrams = []
5
11
  let match
6
12
  while ((match = regex.exec(text)) !== null) {
@@ -13,27 +19,261 @@ export function extractMermaidDiagrams(text) {
13
19
  return diagrams
14
20
  }
15
21
 
16
- export function escapeSvgXml(str = '') {
22
+ export function escapeSvgXml(str = "") {
17
23
  return String(str)
18
- .replace(/&/g, '&')
19
- .replace(/</g, '&lt;')
20
- .replace(/>/g, '&gt;')
21
- .replace(/"/g, '&quot;')
22
- .replace(/'/g, '&apos;')
24
+ .replace(/&/g, "&amp;")
25
+ .replace(/</g, "&lt;")
26
+ .replace(/>/g, "&gt;")
27
+ .replace(/"/g, "&quot;")
28
+ .replace(/'/g, "&apos;")
29
+ }
30
+
31
+ const DIAGRAM_CACHE = new Map()
32
+ const MAX_CACHE_SIZE = 250
33
+
34
+ export function getCachedDiagram(hash) {
35
+ return DIAGRAM_CACHE.get(hash)
36
+ }
37
+
38
+ export function setCachedDiagram(hash, svg) {
39
+ if (DIAGRAM_CACHE.size >= MAX_CACHE_SIZE) {
40
+ const firstKey = DIAGRAM_CACHE.keys().next().value
41
+ DIAGRAM_CACHE.delete(firstKey)
42
+ }
43
+ DIAGRAM_CACHE.set(hash, svg)
44
+ }
45
+
46
+ export function detectDiagramType(code = "") {
47
+ const clean = code.trim().toLowerCase()
48
+ if (clean.startsWith("pie")) return "pie"
49
+ if (clean.startsWith("xychart") || clean.startsWith("xychart-beta")) return "xychart"
50
+ if (clean.startsWith("sequencediagram")) return "sequence"
51
+ if (clean.startsWith("flowchart") || clean.startsWith("graph")) return "flowchart"
52
+ if (clean.startsWith("statediagram")) return "state"
53
+ if (clean.startsWith("classdiagram")) return "class"
54
+ return "code"
55
+ }
56
+
57
+ export function renderPieChartSvg(code, title = "Pie Chart") {
58
+ const lines = code.split("\n").map((l) => l.trim()).filter(Boolean)
59
+ let extractedTitle = title
60
+ const slices = []
61
+
62
+ for (const line of lines) {
63
+ const titleMatch = line.match(/^title\s+(?:"([^"]+)"|(.+))$/i)
64
+ if (titleMatch) {
65
+ extractedTitle = titleMatch[1] || titleMatch[2]
66
+ continue
67
+ }
68
+ const sliceMatch = line.match(/^(?:"([^"]+)"|([\w\s-]+))\s*:\s*([\d.]+)/)
69
+ if (sliceMatch) {
70
+ const label = sliceMatch[1] || sliceMatch[2]
71
+ const val = parseFloat(sliceMatch[3])
72
+ if (!isNaN(val) && val > 0) {
73
+ slices.push({ label: label.trim(), val })
74
+ }
75
+ }
76
+ }
77
+
78
+ if (slices.length < 2) return null
79
+
80
+ const total = slices.reduce((acc, s) => acc + s.val, 0)
81
+ const colors = ["#89b4fa", "#a6e3a1", "#f9e2af", "#f38ba8", "#cba6f7", "#94e2d5", "#fab387", "#74c7ec"]
82
+
83
+ const cx = 220
84
+ const cy = 200
85
+ const r = 120
86
+ const innerR = 60
87
+
88
+ let currentAngle = -Math.PI / 2
89
+ const pathElements = []
90
+ const legendElements = []
91
+
92
+ slices.forEach((slice, i) => {
93
+ const sliceAngle = (slice.val / total) * 2 * Math.PI
94
+ const endAngle = currentAngle + sliceAngle
95
+ const color = colors[i % colors.length]
96
+
97
+ const x1 = cx + r * Math.cos(currentAngle)
98
+ const y1 = cy + r * Math.sin(currentAngle)
99
+ const x2 = cx + r * Math.cos(endAngle)
100
+ const y2 = cy + r * Math.sin(endAngle)
101
+
102
+ const ix1 = cx + innerR * Math.cos(endAngle)
103
+ const iy1 = cy + innerR * Math.sin(endAngle)
104
+ const ix2 = cx + innerR * Math.cos(currentAngle)
105
+ const iy2 = cy + innerR * Math.sin(currentAngle)
106
+
107
+ const largeArc = sliceAngle > Math.PI ? 1 : 0
108
+ const d = `M ${x1} ${y1} A ${r} ${r} 0 ${largeArc} 1 ${x2} ${y2} L ${ix1} ${iy1} A ${innerR} ${innerR} 0 ${largeArc} 0 ${ix2} ${iy2} Z`
109
+
110
+ pathElements.push(`<path d="${d}" fill="${color}" stroke="#181825" stroke-width="2"/>`)
111
+
112
+ const pct = ((slice.val / total) * 100).toFixed(1)
113
+ const legendY = 90 + i * 28
114
+ legendElements.push(`
115
+ <rect x="420" y="${legendY - 12}" width="14" height="14" rx="3" fill="${color}" />
116
+ <text x="444" y="${legendY}" fill="#cdd6f4" font-family="-apple-system, sans-serif" font-size="13" font-weight="500">${escapeSvgXml(slice.label)}</text>
117
+ <text x="740" y="${legendY}" fill="#a6adc8" font-family="monospace" font-size="13" text-anchor="end">${pct}% (${slice.val})</text>
118
+ `)
119
+
120
+ currentAngle = endAngle
121
+ })
122
+
123
+ const safeTitle = escapeSvgXml(extractedTitle)
124
+ const height = Math.max(360, 110 + slices.length * 30)
125
+
126
+ return `<?xml version="1.0" encoding="UTF-8"?>
127
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 780 ${height}" width="780" height="${height}">
128
+ <desc>${escapeSvgXml(code)}</desc>
129
+ <defs>
130
+ <linearGradient id="pie-bg" x1="0%" y1="0%" x2="100%" y2="100%">
131
+ <stop offset="0%" stop-color="#1e1e2e"/>
132
+ <stop offset="100%" stop-color="#181825"/>
133
+ </linearGradient>
134
+ </defs>
135
+ <rect width="100%" height="100%" rx="12" fill="url(#pie-bg)" stroke="#313244" stroke-width="2"/>
136
+ <circle cx="28" cy="28" r="6" fill="#f38ba8" />
137
+ <circle cx="48" cy="28" r="6" fill="#f9e2af" />
138
+ <circle cx="68" cy="28" r="6" fill="#a6e3a1" />
139
+ <text x="96" y="32" fill="#cdd6f4" font-family="-apple-system, sans-serif" font-size="14" font-weight="600">${safeTitle}</text>
140
+ <line x1="16" y1="48" x2="764" y2="48" stroke="#313244" stroke-width="1"/>
141
+ <g>${pathElements.join("\n")}</g>
142
+ <g>${legendElements.join("\n")}</g>
143
+ </svg>`
144
+ }
145
+
146
+ export function renderXyChartSvg(code, title = "Chart") {
147
+ const lines = code.split("\n").map((l) => l.trim()).filter(Boolean)
148
+ let extractedTitle = title
149
+ let xLabels = []
150
+ let barVals = []
151
+ let lineVals = []
152
+
153
+ for (const line of lines) {
154
+ const titleMatch = line.match(/^title\s+(?:"([^"]+)"|(.+))$/i)
155
+ if (titleMatch) {
156
+ extractedTitle = titleMatch[1] || titleMatch[2]
157
+ continue
158
+ }
159
+ const xMatch = line.match(/^x-axis\s*\[(.*)\]/i)
160
+ if (xMatch) {
161
+ xLabels = xMatch[1].split(",").map((s) => s.replace(/["']/g, "").trim()).filter(Boolean)
162
+ continue
163
+ }
164
+ const barMatch = line.match(/^bar\s*\[(.*)\]/i)
165
+ if (barMatch) {
166
+ barVals = barMatch[1].split(",").map((s) => parseFloat(s.trim())).filter((n) => !isNaN(n))
167
+ continue
168
+ }
169
+ const lineMatch = line.match(/^line\s*\[(.*)\]/i)
170
+ if (lineMatch) {
171
+ lineVals = lineMatch[1].split(",").map((s) => parseFloat(s.trim())).filter((n) => !isNaN(n))
172
+ continue
173
+ }
174
+ }
175
+
176
+ const count = Math.max(xLabels.length, barVals.length, lineVals.length)
177
+ if (count < 2) return null
178
+
179
+ const allVals = [...barVals, ...lineVals]
180
+ const maxVal = Math.max(...allVals, 1)
181
+
182
+ const width = 780
183
+ const height = 400
184
+ const plotX = 80
185
+ const plotY = 70
186
+ const plotW = 660
187
+ const plotH = 260
188
+
189
+ const colW = plotW / count
190
+ const barWidth = Math.min(36, colW * 0.5)
191
+
192
+ // Gridlines
193
+ const gridLines = []
194
+ for (let step = 0; step <= 4; step++) {
195
+ const yVal = ((maxVal * step) / 4).toFixed(0)
196
+ const yPos = plotY + plotH - (plotH * step) / 4
197
+ gridLines.push(`
198
+ <line x1="${plotX}" y1="${yPos}" x2="${plotX + plotW}" y2="${yPos}" stroke="#313244" stroke-width="1" stroke-dasharray="4"/>
199
+ <text x="${plotX - 12}" y="${yPos + 4}" fill="#a6adc8" font-family="monospace" font-size="11" text-anchor="end">${yVal}</text>
200
+ `)
201
+ }
202
+
203
+ // Bars
204
+ const barsElements = []
205
+ barVals.forEach((val, i) => {
206
+ const bH = (val / maxVal) * plotH
207
+ const bx = plotX + i * colW + (colW - barWidth) / 2
208
+ const by = plotY + plotH - bH
209
+ barsElements.push(`
210
+ <rect x="${bx}" y="${by}" width="${barWidth}" height="${bH}" rx="4" fill="#89b4fa" fill-opacity="0.85" />
211
+ <text x="${bx + barWidth / 2}" y="${by - 6}" fill="#cdd6f4" font-family="monospace" font-size="10" text-anchor="middle">${val}</text>
212
+ `)
213
+ })
214
+
215
+ // Line points
216
+ const linePoints = []
217
+ lineVals.forEach((val, i) => {
218
+ const lx = plotX + i * colW + colW / 2
219
+ const ly = plotY + plotH - (val / maxVal) * plotH
220
+ linePoints.push({ x: lx, y: ly, val })
221
+ })
222
+
223
+ let lineSvg = ""
224
+ if (linePoints.length >= 2) {
225
+ const d = linePoints.map((p, i) => `${i === 0 ? "M" : "L"} ${p.x} ${p.y}`).join(" ")
226
+ const dots = linePoints.map((p) => `<circle cx="${p.x}" cy="${p.y}" r="4" fill="#f38ba8" stroke="#181825" stroke-width="2"/>`).join("")
227
+ lineSvg = `<path d="${d}" fill="none" stroke="#f38ba8" stroke-width="3"/>${dots}`
228
+ }
229
+
230
+ // X Labels
231
+ const xLabelElements = []
232
+ for (let i = 0; i < count; i++) {
233
+ const lbl = xLabels[i] || `T${i + 1}`
234
+ const lx = plotX + i * colW + colW / 2
235
+ xLabelElements.push(`
236
+ <text x="${lx}" y="${plotY + plotH + 24}" fill="#a6adc8" font-family="-apple-system, sans-serif" font-size="12" text-anchor="middle">${escapeSvgXml(lbl)}</text>
237
+ `)
238
+ }
239
+
240
+ const safeTitle = escapeSvgXml(extractedTitle)
241
+
242
+ return `<?xml version="1.0" encoding="UTF-8"?>
243
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">
244
+ <desc>${escapeSvgXml(code)}</desc>
245
+ <defs>
246
+ <linearGradient id="xy-bg" x1="0%" y1="0%" x2="100%" y2="100%">
247
+ <stop offset="0%" stop-color="#1e1e2e"/>
248
+ <stop offset="100%" stop-color="#181825"/>
249
+ </linearGradient>
250
+ </defs>
251
+ <rect width="100%" height="100%" rx="12" fill="url(#xy-bg)" stroke="#313244" stroke-width="2"/>
252
+ <circle cx="28" cy="28" r="6" fill="#f38ba8" />
253
+ <circle cx="48" cy="28" r="6" fill="#f9e2af" />
254
+ <circle cx="68" cy="28" r="6" fill="#a6e3a1" />
255
+ <text x="96" y="32" fill="#cdd6f4" font-family="-apple-system, sans-serif" font-size="14" font-weight="600">${safeTitle}</text>
256
+ <line x1="16" y1="48" x2="${width - 16}" y2="48" stroke="#313244" stroke-width="1"/>
257
+ <g>${gridLines.join("\n")}</g>
258
+ <g>${barsElements.join("\n")}</g>
259
+ <g>${lineSvg}</g>
260
+ <g>${xLabelElements.join("\n")}</g>
261
+ </svg>`
23
262
  }
24
263
 
25
- export function generateDiagramSvg(code, title = 'Mermaid Diagram') {
26
- const lines = code.split('\n').slice(0, 30)
264
+ export function renderCodeCardSvg(code, title = "Mermaid Diagram") {
265
+ const lines = code.split("\n").slice(0, 30)
27
266
  const lineSpans = lines.map((line, i) => {
28
267
  const escaped = escapeSvgXml(line)
29
- return `<tspan x="24" dy="${i === 0 ? '0' : '1.4em'}">${escaped}</tspan>`
30
- }).join('')
268
+ return `<tspan x="24" dy="${i === 0 ? "0" : "1.4em"}">${escaped}</tspan>`
269
+ }).join("")
31
270
 
32
271
  const height = Math.max(160, Math.min(800, lines.length * 24 + 100))
33
272
  const safeTitle = escapeSvgXml(title)
34
273
 
35
274
  return `<?xml version="1.0" encoding="UTF-8"?>
36
275
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 ${height}" width="800" height="${height}">
276
+ <desc>${escapeSvgXml(code)}</desc>
37
277
  <defs>
38
278
  <linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
39
279
  <stop offset="0%" stop-color="#1e1e2e"/>
@@ -52,16 +292,62 @@ export function generateDiagramSvg(code, title = 'Mermaid Diagram') {
52
292
  </svg>`
53
293
  }
54
294
 
295
+ export function generateDiagramSvg(code, title = "Diagram") {
296
+ const hash = createHash("sha256").update(code).digest("hex")
297
+ const cached = getCachedDiagram(hash)
298
+ if (cached) return cached
299
+
300
+ const type = detectDiagramType(code)
301
+ let svg = null
302
+
303
+ if (type === "pie") {
304
+ svg = renderPieChartSvg(code, title)
305
+ } else if (type === "xychart") {
306
+ svg = renderXyChartSvg(code, title)
307
+ }
308
+
309
+ if (!svg) {
310
+ svg = renderCodeCardSvg(code, title)
311
+ }
312
+
313
+ setCachedDiagram(hash, svg)
314
+ return svg
315
+ }
316
+
317
+ export async function convertSvgToPng(svgContent) {
318
+ const rnd = Math.random().toString(36).slice(2, 8)
319
+ const inPath = join(tmpdir(), `chart-${Date.now()}-${rnd}.svg`)
320
+ const outPath = join(tmpdir(), `chart-${Date.now()}-${rnd}.png`)
321
+
322
+ try {
323
+ writeFileSync(inPath, svgContent, "utf-8")
324
+ await new Promise((resolve, reject) => {
325
+ const proc = spawn("ffmpeg", ["-y", "-i", inPath, "-update", "1", "-frames:v", "1", outPath])
326
+ proc.on("error", reject)
327
+ proc.on("close", (code) => {
328
+ if (code === 0) resolve()
329
+ else reject(new Error(`ffmpeg exited with code ${code}`))
330
+ })
331
+ })
332
+ return readFileSync(outPath)
333
+ } catch {
334
+ return null
335
+ } finally {
336
+ try { unlinkSync(inPath) } catch { /* safe best-effort temp file cleanup */ }
337
+ try { unlinkSync(outPath) } catch { /* safe best-effort temp file cleanup */ }
338
+ }
339
+ }
340
+
55
341
  export function formatMarkdownTables(text) {
56
- if (!text || typeof text !== 'string') return text
342
+ if (!text || typeof text !== "string") return text
57
343
  const tableRegex = /((?:^|\n)\|[^\n]+\|\n\|[\s\-:|]+\|\n(?:\|[^\n]+\|\n?)+)/g
58
344
 
59
345
  return text.replace(tableRegex, (match) => {
60
- const rawLines = match.trim().split('\n')
346
+ const rawLines = match.trim().split("\n")
61
347
  if (rawLines.length < 3) return match
62
348
 
63
349
  const rows = rawLines.map((line) => {
64
- const cells = line.split('|').slice(1, -1).map((c) => c.trim())
350
+ const cells = line.split("|").slice(1, -1).map((c) => c.trim())
65
351
  return cells
66
352
  })
67
353
 
@@ -77,19 +363,19 @@ export function formatMarkdownTables(text) {
77
363
 
78
364
  const formattedRows = rows.map((row, rowIdx) => {
79
365
  if (rowIdx === 1) {
80
- return colWidths.map((w) => '-'.repeat(Math.max(w, 3))).join(' | ')
366
+ return colWidths.map((w) => "-".repeat(Math.max(w, 3))).join(" | ")
81
367
  }
82
- return row.map((cell, colIdx) => cell.padEnd(colWidths[colIdx] || 3)).join(' | ')
368
+ return row.map((cell, colIdx) => cell.padEnd(colWidths[colIdx] || 3)).join(" | ")
83
369
  })
84
370
 
85
- const alignedTable = formattedRows.join('\n')
371
+ const alignedTable = formattedRows.join("\n")
86
372
  return `\n\`\`\`\n${alignedTable}\n\`\`\`\n`
87
373
  })
88
374
  }
89
375
 
90
376
  export function processDiagramsAndTables(rawText, options = {}) {
91
377
  const { artifactPreviews = true } = options
92
- let text = String(rawText || '')
378
+ let text = String(rawText || "")
93
379
  const files = []
94
380
 
95
381
  if (artifactPreviews) {
@@ -98,13 +384,13 @@ export function processDiagramsAndTables(rawText, options = {}) {
98
384
  let diagramIndex = 1
99
385
  for (const diag of diagrams) {
100
386
  const svgContent = generateDiagramSvg(diag.code, `Diagram ${diagramIndex}`)
101
- const base64 = Buffer.from(svgContent, 'utf-8').toString('base64')
387
+ const base64 = Buffer.from(svgContent, "utf-8").toString("base64")
102
388
  files.push({
103
389
  name: `diagram-${diagramIndex}.svg`,
104
- mime: 'image/svg+xml',
105
- kind: 'document',
390
+ mime: "image/svg+xml",
391
+ kind: "document",
106
392
  dataBase64: base64,
107
- bytes: Buffer.from(svgContent, 'utf-8'),
393
+ bytes: Buffer.from(svgContent, "utf-8"),
108
394
  })
109
395
 
110
396
  text = text.replace(diag.fullMatch, `\nšŸ“Š <b>[Diagram ${diagramIndex}: see attachment]</b>\n`)
@@ -116,3 +402,47 @@ export function processDiagramsAndTables(rawText, options = {}) {
116
402
 
117
403
  return { text, files, diagramsCount: files.length }
118
404
  }
405
+
406
+ export async function processDiagramsAndTablesAsync(rawText, options = {}) {
407
+ const { artifactPreviews = true } = options
408
+ let text = String(rawText || "")
409
+ const files = []
410
+
411
+ if (artifactPreviews) {
412
+ const diagrams = extractMermaidDiagrams(text)
413
+ if (diagrams.length > 0) {
414
+ let diagramIndex = 1
415
+ for (const diag of diagrams) {
416
+ const type = detectDiagramType(diag.code)
417
+ const typeLabel = type === "pie" ? "Pie Chart" : type === "xychart" ? "Chart" : "Diagram"
418
+ const title = `${typeLabel} ${diagramIndex}`
419
+ const svgContent = generateDiagramSvg(diag.code, title)
420
+ const pngBytes = await convertSvgToPng(svgContent)
421
+
422
+ if (pngBytes && pngBytes.length > 0) {
423
+ files.push({
424
+ name: `diagram-${diagramIndex}.png`,
425
+ mime: "image/png",
426
+ kind: "photo",
427
+ dataBase64: pngBytes.toString("base64"),
428
+ bytes: pngBytes,
429
+ })
430
+ text = text.replace(diag.fullMatch, `\nšŸ“Š <b>[${title}: see photo preview]</b>\n`)
431
+ } else {
432
+ files.push({
433
+ name: `diagram-${diagramIndex}.svg`,
434
+ mime: "image/svg+xml",
435
+ kind: "document",
436
+ dataBase64: Buffer.from(svgContent, "utf-8").toString("base64"),
437
+ bytes: Buffer.from(svgContent, "utf-8"),
438
+ })
439
+ text = text.replace(diag.fullMatch, `\nšŸ“Š <b>[${title}: see attachment]</b>\n`)
440
+ }
441
+ diagramIndex++
442
+ }
443
+ }
444
+ text = formatMarkdownTables(text)
445
+ }
446
+
447
+ return { text, files, diagramsCount: files.length }
448
+ }
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
@@ -36,6 +36,7 @@ export const PluginConfig = z.object({
36
36
  streaming: z.boolean().default(false).description('If true, edit one Telegram message while tokens arrive; default off'),
37
37
  streamEditIntervalMs: z.number().default(1200),
38
38
  progressEnabled: z.boolean().default(true),
39
+ mediaGroupDebounceMs: z.number().default(650),
39
40
  showReasoning: z.boolean().default(true).description('Display model reasoning/thought process in chat'),
40
41
  thoughtCollapse: z.boolean().default(true).description('Collapse finished thoughts into expandable blockquote'),
41
42
  approvalsEnabled: z.boolean().default(true),
@@ -102,6 +103,15 @@ export const PluginConfig = z.object({
102
103
  maxChars: z.number().default(4000),
103
104
  voiceSummary: z.boolean().default(false).description('Speak concise TL;DR summary while full text is sent to chat'),
104
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(),
105
115
  agent: z.object({
106
116
  provider: z.string().default(''),
107
117
  model: z.string().default(''),