@goodandready/dsh-messenger-gateway 0.4.24 β†’ 0.4.25

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/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),
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
- base += `\n\n[Extracted text from file${truncNote}]:\n\`\`\`\n${parsed.text}\n\`\`\``
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 === '.pdf') {
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') {
@@ -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'
@@ -289,7 +289,7 @@ export async function runGatewayTurn(gw, chat, input, signal) {
289
289
  const thoughtHeader = String(gw.resolveLocale(input)).toLowerCase().startsWith('zh') ? '🧠 <i>思考过程:</i>' : '🧠 <i>Thought process:</i>'
290
290
  rawAnswer = `${quoteTag}${thoughtHeader}\n${escapeHtml(parsedReasoning.thought)}</blockquote>\n\n${cleanContent}`
291
291
  }
292
- const processed = processDiagramsAndTables(rawAnswer, {
292
+ const processed = await processDiagramsAndTablesAsync(rawAnswer, {
293
293
  artifactPreviews: gw.tg().artifactPreviews !== false,
294
294
  })
295
295
  const answer = processed.text
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.25",
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",