@goodandready/dsh-messenger-gateway 0.4.31 β†’ 0.4.33

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.
@@ -326,7 +326,7 @@ export class TelegramAdapter {
326
326
  callback_query_id: update.callback_query.id,
327
327
  text: 'Access denied',
328
328
  show_alert: true,
329
- }).catch(() => {})
329
+ }).catch((e) => { this.logger?.debug?.('answerCallbackQuery access denied failed:', e?.message || e) })
330
330
  return
331
331
  }
332
332
  try { await this.onCallback?.(this.wrapCallback(update.callback_query)) } catch (e) {
@@ -1,3 +1,4 @@
1
+ import { escapeHtml } from './telegram-format.js'
1
2
  import { realpathSync } from 'node:fs'
2
3
  import { readdir, stat, readFile } from 'node:fs/promises'
3
4
  import { resolve, normalize, relative, join, extname, isAbsolute, sep, dirname } from 'node:path'
@@ -87,7 +88,8 @@ export function resolveInside(base, candidate = '.') {
87
88
 
88
89
  export async function listFiles(baseCwd, subPath = '.', opts = {}) {
89
90
  const { maxEntries = 50, showHidden = false } = opts
90
- const { base, target, relativePath } = resolveSafePath(baseCwd, subPath)
91
+ const target = resolveInside(baseCwd, subPath)
92
+ const { relativePath } = resolveSafePath(baseCwd, subPath)
91
93
 
92
94
  let st
93
95
  try {
@@ -102,7 +104,7 @@ export async function listFiles(baseCwd, subPath = '.', opts = {}) {
102
104
  isDirectory: false,
103
105
  currentPath: relativePath,
104
106
  entries: [{ name: relativePath, size: st.size, isDirectory: false }],
105
- formattedText: `πŸ“„ <b>${relativePath}</b> (${formatFileSize(st.size)})\nDownload: <code>/get ${relativePath}</code>`,
107
+ formattedText: `πŸ“„ <b>${escapeHtml(relativePath)}</b> (${formatFileSize(st.size)})\nDownload: <code>/get ${escapeHtml(relativePath)}</code>`,
106
108
  }
107
109
  }
108
110
 
@@ -152,9 +154,9 @@ export async function listFiles(baseCwd, subPath = '.', opts = {}) {
152
154
 
153
155
  for (const e of sliced) {
154
156
  if (e.isDirectory) {
155
- lines.push(`πŸ“ <code>${e.name}/</code>`)
157
+ lines.push(`πŸ“ <code>${escapeHtml(e.name)}/</code>`)
156
158
  } else {
157
- lines.push(`πŸ“„ <code>${e.name}</code> (${formatFileSize(e.size)})`)
159
+ lines.push(`πŸ“„ <code>${escapeHtml(e.name)}</code> (${formatFileSize(e.size)})`)
158
160
  }
159
161
  }
160
162
 
@@ -175,7 +177,8 @@ export async function listFiles(baseCwd, subPath = '.', opts = {}) {
175
177
  }
176
178
 
177
179
  export async function getFileForDownload(baseCwd, relativePath, maxBytes = 50 * 1024 * 1024) {
178
- const { target, relativePath: safeRel } = resolveSafePath(baseCwd, relativePath)
180
+ const target = resolveInside(baseCwd, relativePath)
181
+ const { relativePath: safeRel } = resolveSafePath(baseCwd, relativePath)
179
182
  let st
180
183
  try {
181
184
  st = await stat(target)
@@ -243,7 +246,7 @@ export async function handleGetCommand(agentCwd, targetRel, maxDocBytes = 50 * 1
243
246
  dataBase64: res.bytes.toString('base64'),
244
247
  }
245
248
  return {
246
- text: `πŸ“„ File: <b>${res.name}</b> (${formatFileSize(res.size)})`,
249
+ text: `πŸ“„ File: <b>${escapeHtml(res.name)}</b> (${formatFileSize(res.size)})`,
247
250
  files: [file],
248
251
  }
249
252
  }
@@ -1,3 +1,4 @@
1
+ import { escapeHtml } from './telegram-format.js'
1
2
  import { t } from './locales/index.js'
2
3
  import {
3
4
  parseCallbackData, parseAskCallback, targetMatchesAsk,
@@ -157,16 +158,17 @@ export async function handleGatewayCallback(gw, cb) {
157
158
  }
158
159
  const { provider, model } = stored
159
160
  try {
160
- const adm = gw.ctx.get('agentDefaultModel')
161
+ let saved = false
162
+ const adm = gw.ctx.get?.('agentDefaultModel') || gw.ctx.agentDefaultModel
161
163
  if (adm?.saveSelection) {
162
164
  await adm.saveSelection({ provider, model })
165
+ saved = true
163
166
  }
164
- gw.config.agent = { ...gw.config.agent, provider, model }
165
- try {
166
- await gw.hooks?.persistAgentModel?.({ provider, model })
167
- } catch (e) {
168
- gw.ctx.logger?.warn?.(`persist agent model: ${e.message}`)
167
+ if (!saved && gw.hooks?.persistAgentModel) {
168
+ await gw.hooks.persistAgentModel({ provider, model })
169
+ saved = true
169
170
  }
171
+ gw.config.agent = { ...gw.config.agent, provider, model }
170
172
  await cb.answer(t('ask.chose', { choice: model }, 'en'))
171
173
  try {
172
174
  if (cb.editMessage) await cb.editMessage(t('model.switched', { provider, model }, 'en'), REMOVE_KEYBOARD)
@@ -44,14 +44,14 @@ export async function handleGatewayCommand(gw, key, text, input) {
44
44
  return reply(sub === 'zh' ? 'θ―­θ¨€ε·²εˆ‡ζ’δΈΊδΈ­ζ–‡ (zh)' : 'Language switched to English (en)')
45
45
  }
46
46
  const cur = gw.chatLocales.get(chatId) || gw.config?.defaultLocale || 'en'
47
- return reply(`Current language: <b>${cur}</b>\nSwitch: <code>/lang en</code> or <code>/lang zh</code>`)
47
+ return reply(`Current language: <b>${escapeHtml(cur)}</b>\nSwitch: <code>/lang en</code> or <code>/lang zh</code>`)
48
48
  }
49
49
 
50
50
  if (cmd === '/bind') {
51
51
  const targetRole = parts[1]?.toLowerCase()
52
52
  if (!targetRole || targetRole === 'list') {
53
53
  const cur = gw.personas.getPersonaForChat(chatId, threadId)
54
- return reply(`${t('persona.title', {}, locale)}\nCurrent bound role: <b>${cur}</b>\nUsage: <code>/bind &lt;role&gt;</code> (or /bind reset)`)
54
+ return reply(`${t('persona.title', {}, locale)}\nCurrent bound role: <b>${escapeHtml(cur)}</b>\nUsage: <code>/bind &lt;role&gt;</code> (or /bind reset)`)
55
55
  }
56
56
  if (targetRole === 'reset' || targetRole === 'default') {
57
57
  gw.personas.set(chatId, 'default', threadId)
@@ -67,7 +67,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
67
67
  const presetName = parts[1]
68
68
  if (!presetName || presetName === 'list') {
69
69
  const cur = gw.personas.getPreset(chatId, threadId) || '(none)'
70
- return reply(`🎭 <b>Presets:</b>\nCurrent topic preset: <code>${cur}</code>\nUsage: <code>/preset &lt;name&gt;</code> or <code>/preset reset</code>`)
70
+ return reply(`🎭 <b>Presets:</b>\nCurrent topic preset: <code>${escapeHtml(cur)}</code>\nUsage: <code>/preset &lt;name&gt;</code> or <code>/preset reset</code>`)
71
71
  }
72
72
  if (presetName === 'reset' || presetName === 'clear') {
73
73
  gw.personas.setPreset(chatId, threadId, null)
@@ -85,7 +85,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
85
85
  const lines = [t('cron.list_title', {}, locale)]
86
86
  for (const task of list) {
87
87
  const left = formatRemaining(task.dueAt - Date.now(), locale)
88
- lines.push(`β€’ <code>${task.id}</code> (every ${formatRemaining(task.intervalMs, locale)}, next in ${left}): ${task.prompt || task.text}`)
88
+ lines.push(`β€’ <code>${escapeHtml(task.id)}</code> (every ${formatRemaining(task.intervalMs, locale)}, next in ${left}): ${escapeHtml(task.prompt || task.text || "")}`)
89
89
  }
90
90
  lines.push('\nCancel: <code>/cron cancel ID</code>')
91
91
  return reply(lines.join('\n'))
@@ -94,7 +94,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
94
94
  const targetId = parts[2]
95
95
  if (!targetId) return reply('Specify cron task ID: <code>/cron cancel ID</code>')
96
96
  const ok = await gw.scheduler.cancel(targetId, chatId)
97
- return reply(ok ? t('cron.cancelled', { id: targetId }, locale) : `Task not found: <code>${targetId}</code>`)
97
+ return reply(ok ? t('cron.cancelled', { id: targetId }, locale) : `Task not found: <code>${escapeHtml(targetId)}</code>`)
98
98
  }
99
99
  const specArg = parts[1]
100
100
  const promptArg = parts.slice(2).join(' ')
@@ -182,7 +182,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
182
182
  const toolsList = []
183
183
  if (tools?.tools) {
184
184
  for (const [name, tDef] of tools.tools.entries()) {
185
- toolsList.push(`β€’ <b>${name}</b>: ${tDef.description || '(no description)'}`)
185
+ toolsList.push(`β€’ <b>${escapeHtml(name)}</b>: ${escapeHtml(tDef.description || '(no description)')}`)
186
186
  }
187
187
  }
188
188
  if (!toolsList.length) {
@@ -285,7 +285,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
285
285
 
286
286
  const chat = gw.chats.get(key)
287
287
  if (chat?.agent?.session?.id) {
288
- registerSessionInWorkspace(gw.ctx, chat.agent.session.id, realCwd, gw.ctx?.logger).catch(() => {})
288
+ registerSessionInWorkspace(gw.ctx, chat.agent.session.id, realCwd, gw.ctx?.logger).catch((e) => { gw.ctx?.logger?.debug?.('registerSessionInWorkspace error:', e?.message || e) })
289
289
  }
290
290
 
291
291
  const lines = [
@@ -524,7 +524,9 @@ export async function handleGatewayCommand(gw, key, text, input) {
524
524
  const titleSnap = await sessionQuery.readTitle(id)
525
525
  title = titleSnap?.title || titleSnap?.value || ''
526
526
  } catch { /* best effort */ }
527
- if (!title) title = r.header.title || id
527
+ if (!title || title.startsWith('Channel: Messenger') || title.startsWith('[Channel: Messenger')) {
528
+ title = (r.header.title && !r.header.title.startsWith('Channel: Messenger') && !r.header.title.startsWith('[Channel: Messenger')) ? r.header.title : id
529
+ }
528
530
  const cwd = r.header.cwd || r.header.meta?.cwd || ''
529
531
  const dir = cwd ? cwd.split(/[\\/]/).filter(Boolean).slice(-2).join('/') : ''
530
532
  return { id, title, dir }
@@ -533,8 +535,8 @@ export async function handleGatewayCommand(gw, key, text, input) {
533
535
  gw.recentSessions.set(key, items)
534
536
  const lines = ['πŸ“‹ <b>Recent Sessions:</b>', '']
535
537
  items.forEach((item, index) => {
536
- const dirSuffix = item.dir ? ` (<i>${item.dir}</i>)` : ''
537
- lines.push(`${index + 1}. <b>${item.title}</b>${dirSuffix}\n <code>/resume ${index + 1}</code>`)
538
+ const dirSuffix = item.dir ? ` (<i>${escapeHtml(item.dir)}</i>)` : ''
539
+ lines.push(`${index + 1}. <b>${escapeHtml(item.title)}</b>${dirSuffix}\n <code>/resume ${index + 1}</code>`)
538
540
  })
539
541
  lines.push('', 'Switch using <code>/resume &lt;number&gt;</code>')
540
542
  return reply(lines.join('\n'))
@@ -688,21 +690,42 @@ export async function handleGatewayCommand(gw, key, text, input) {
688
690
  }
689
691
 
690
692
  if (cmd === '/model') {
693
+ const wantsList = /^(?:list|ls|all)$/i.test(parts[1] || '')
694
+ if (wantsList) {
695
+ try {
696
+ const current = gw.resolveAgentModel()
697
+ const catalog = await listModelCatalog(gw.ctx, current)
698
+ const lines = ['🧠 <b>Models</b>', `Current: <code>${escapeHtml(current.provider)}/${escapeHtml(current.model)}</code>`, '']
699
+ for (const p of catalog.providers) {
700
+ lines.push(`<b>${escapeHtml(p.name || p.id)}</b>`)
701
+ for (const m of catalog.modelsByProvider.get(p.id) || []) {
702
+ const mark = (m.id === current.model && p.id === current.provider) ? ' βœ…' : ''
703
+ lines.push(`β€’ <code>/model ${escapeHtml(p.id)} ${escapeHtml(m.id)}</code>${mark}`)
704
+ }
705
+ lines.push('')
706
+ }
707
+ return reply(lines.join('\n'))
708
+ } catch (e) {
709
+ return reply(`Failed to list models: ${e.message}`)
710
+ }
711
+ }
712
+
691
713
  if (parts.length >= 3) {
692
714
  if (!gw.isUserAllowed(userId)) return reply(t('msg.not_allowed', {}, locale))
693
715
  const provider = parts[1]
694
716
  const model = parts.slice(2).join(' ')
695
717
  try {
696
- const adm = gw.ctx.get('agentDefaultModel')
718
+ let saved = false
719
+ const adm = gw.ctx.get?.('agentDefaultModel') || gw.ctx.agentDefaultModel
697
720
  if (adm?.saveSelection) {
698
721
  await adm.saveSelection({ provider, model })
722
+ saved = true
699
723
  }
700
- gw.config.agent = { ...gw.config.agent, provider, model }
701
- try {
702
- await gw.hooks?.persistAgentModel?.({ provider, model })
703
- } catch (e) {
704
- gw.ctx.logger?.warn?.(`persist agent model: ${e.message}`)
724
+ if (!saved && gw.hooks?.persistAgentModel) {
725
+ await gw.hooks.persistAgentModel({ provider, model })
726
+ saved = true
705
727
  }
728
+ gw.config.agent = { ...gw.config.agent, provider, model }
706
729
  return reply(t('model.switched', { provider, model }, locale))
707
730
  } catch (e) {
708
731
  return reply(`Failed to switch model: ${e.message}`)
@@ -712,7 +735,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
712
735
  const current = gw.resolveAgentModel()
713
736
  const catalog = await listModelCatalog(gw.ctx, current)
714
737
  if (!catalog.providers.length) {
715
- return reply(`Current model: <code>${current.provider}/${current.model}</code>\nSwitch: <code>/model &lt;provider&gt; &lt;model&gt;</code>`)
738
+ return reply(`Current model: <code>${escapeHtml(current.provider)}/${escapeHtml(current.model)}</code>\nSwitch: <code>/model &lt;provider&gt; &lt;model&gt;</code>`)
716
739
  }
717
740
  const kb = buildProvidersKeyboard(catalog.providers, current)
718
741
  return reply([
@@ -778,7 +801,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
778
801
  '',
779
802
  ...active.map((tItem) => {
780
803
  const left = formatRemaining(tItem.dueAt - Date.now(), locale)
781
- return `β€’ <code>${tItem.id}</code> (in ${left}): ${tItem.text}`
804
+ return `β€’ <code>${escapeHtml(tItem.id)}</code> (in ${left}): ${escapeHtml(tItem.text || '')}`
782
805
  }),
783
806
  '',
784
807
  'Cancel: <code>/remind cancel ID</code>',
@@ -789,7 +812,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
789
812
  const targetId = parts[2]?.trim()
790
813
  if (!targetId) return reply('Specify reminder ID: <code>/remind cancel ID</code>')
791
814
  const ok = await gw.scheduler.cancel(targetId, chatId)
792
- return reply(ok ? `βœ… Reminder <code>${targetId}</code> cancelled.` : `❌ Reminder <code>${targetId}</code> not found.`)
815
+ return reply(ok ? `βœ… Reminder <code>${escapeHtml(targetId)}</code> cancelled.` : `❌ Reminder <code>${escapeHtml(targetId)}</code> not found.`)
793
816
  }
794
817
  const timeArg = parts[1]
795
818
  const textArg = parts.slice(2).join(' ').trim()
@@ -851,10 +874,10 @@ export async function handleGatewayCommand(gw, key, text, input) {
851
874
  try {
852
875
  const res = await tgAdapter.createForumTopic(chatId, topicName)
853
876
  const newThreadId = res?.message_thread_id
854
- await reply(`🎯 Created new topic <b>«${topicName}»</b> (ID: <code>${newThreadId}</code>).\nSwitch to the topic to continue working!`)
877
+ await reply(`🎯 Created new topic <b>«${escapeHtml(topicName)}»</b> (ID: <code>${newThreadId}</code>).\nSwitch to the topic to continue working!`)
855
878
  if (newThreadId) {
856
879
  await tgAdapter.sendTo(chatId, {
857
- text: `πŸ‘‹ Hello! This is an isolated session for task <b>Β«${topicName}Β»</b>.\nHow can I help?`,
880
+ text: `πŸ‘‹ Hello! This is an isolated session for task <b>Β«${escapeHtml(topicName)}Β»</b>.\nHow can I help?`,
858
881
  }, { threadId: newThreadId })
859
882
  }
860
883
  return
@@ -888,7 +911,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
888
911
  `β€’ <b>Uptime:</b> ${hh}:${mm}:${ss}`,
889
912
  `β€’ <b>Active chats:</b> ${gw.chats.size}`,
890
913
  `β€’ <b>Queued reminders:</b> ${activeReminders}`,
891
- `β€’ <b>Active model:</b> <code>${currentModel}</code>`,
914
+ `β€’ <b>Active model:</b> <code>${escapeHtml(currentModel)}</code>`,
892
915
  `β€’ <b>Messages sent:</b> ${gw.stats.sent}`,
893
916
  `β€’ <b>Errors:</b> ${gw.stats.errors}`,
894
917
  ].join('\n'))
@@ -12,7 +12,7 @@ import { speakText, transcribeVoice } from './integrations.js'
12
12
  import { attachInboundPhoto, photoOnlyHint } from './photos.js'
13
13
  import { buildOutboundFiles, stripImageUrls } from './outbound.js'
14
14
  import {
15
- buildStreamPreview, formatProgressLine, createEditScheduler, startTypingHeartbeat, parseReasoningStream
15
+ buildStreamPreview, formatProgressLine, createEditScheduler, startTypingHeartbeat, parseReasoningStream, formatReasoningFinal
16
16
  } from './stream.js'
17
17
  import { escapeHtml } from './telegram-format.js'
18
18
  import { formatCostFooter, normalizeUsage, extractSessionStats, calculateEstimatedCostUsd, checkBudgetThreshold } from './cost-tracker.js'
@@ -139,7 +139,9 @@ export async function answerApproval(gw, chatKeyValue, req, next) {
139
139
  export async function buildUserContent(gw, input, signal) {
140
140
  const { text, attachments = [], replyText, steer, personaOverride, userId } = input
141
141
  const parts = []
142
- parts.push(String(gw.config.agent?.instructionPrefix || MESSENGER_RELAY_INSTRUCTION))
142
+ if (text?.trim()) parts.push(text.trim())
143
+ const relayInstruction = String(gw.config.agent?.instructionPrefix || MESSENGER_RELAY_INSTRUCTION)
144
+ if (relayInstruction) parts.push(`[${relayInstruction}]`)
143
145
  if (gw.config?.memory?.enabled !== false && gw.config?.memory?.autoInject !== false && userId) {
144
146
  try {
145
147
  const recalled = await recallUserMemories({
@@ -206,7 +208,6 @@ export async function buildUserContent(gw, input, signal) {
206
208
  if (photoHint) parts.push(photoHint)
207
209
  const docHint = documentOnlyHint(attachments, text)
208
210
  if (docHint) parts.push(docHint)
209
- if (text?.trim()) parts.push(text.trim())
210
211
  const textBlock = parts.filter(Boolean).join('\n\n')
211
212
  if (textBlock) blocks.unshift({ type: 'text', text: textBlock })
212
213
  if (!blocks.length) blocks.push({ type: 'text', text: '(empty message)' })
@@ -298,14 +299,11 @@ export async function runGatewayTurn(gw, chat, input, signal) {
298
299
  progress = null
299
300
  if (typeof react === 'function') react('').catch?.((e) => { gw.logger?.debug?.('react clear error:', e?.message || e) })
300
301
  const rawText = stripImageUrls(collector.lastText || collector.streamText || collector.parts.join('\n\n'))
301
- const parsedReasoning = parseReasoningStream(rawText, collector.reasoningText)
302
- const cleanContent = stripReasoningPreamble(parsedReasoning.content || rawText)
303
- let rawAnswer = cleanContent
304
- if (parsedReasoning.hasThought && tg.showReasoning !== false) {
305
- const quoteTag = tg.thoughtCollapse !== false ? '<blockquote expandable>' : '<blockquote>'
306
- const thoughtHeader = String(gw.resolveLocale(input)).toLowerCase().startsWith('zh') ? '🧠 <i>思考过程:</i>' : '🧠 <i>Thought process:</i>'
307
- rawAnswer = `${quoteTag}${thoughtHeader}\n${escapeHtml(parsedReasoning.thought)}</blockquote>\n\n${cleanContent}`
308
- }
302
+ const rawAnswer = formatReasoningFinal(rawText, collector.reasoningText, {
303
+ showReasoning: tg.showReasoning !== false,
304
+ thoughtCollapse: tg.thoughtCollapse !== false,
305
+ locale: gw.resolveLocale(input),
306
+ })
309
307
  const processed = await processDiagramsAndTablesAsync(rawAnswer, {
310
308
  artifactPreviews: gw.tg().artifactPreviews !== false,
311
309
  artifactStore: gw.artifactStore,
@@ -399,7 +397,7 @@ export async function runGatewayTurn(gw, chat, input, signal) {
399
397
  gw.sendAlert('status', {
400
398
  title: 'Budget Alert',
401
399
  details: `${warning.message} (Chat: ${input.chatId})`,
402
- }).catch(() => {})
400
+ }).catch((e) => { gw.logger?.debug?.('budgetAlert send error:', e?.message || e) })
403
401
  }
404
402
  }
405
403
  if (gw.config?.memory?.enabled !== false && userId && answer && input.text) {
package/lib/gateway.js CHANGED
@@ -11,6 +11,7 @@ import { resolveNamedHome, listHomes } from './homes.js'
11
11
  import { assistantText } from './text.js'
12
12
  import { collectAssistantParts } from './outbound.js'
13
13
  import { extractTextDelta, extractReasoningDelta, extractToolName } from './stream.js'
14
+ import { clearModelCatalogCache } from './models.js'
14
15
  import { createVoicePrefs } from './voice-prefs.js'
15
16
  import { executeMessengerAsk, releaseCallbacks, rejectPendingAsk } from './ask.js'
16
17
  import { createPersonaStore, BUILTIN_PERSONAS } from './personas.js'
@@ -52,6 +53,7 @@ export class Gateway {
52
53
  this.pendingAsks = new Map()
53
54
  this.adapters = new Map()
54
55
  this.adapterList = []
56
+ this.recentSessions = new Map()
55
57
  // true послС stop(): start() обязан ΠΏΡ€Π΅ΠΊΡ€Π°Ρ‚ΠΈΡ‚ΡŒ Ρ€Π°Π±ΠΎΡ‚Ρƒ, Ссли Π΅Π³ΠΎ ΠΎΠ±ΠΎΠ³Π½Π°Π»ΠΈ.
56
58
  this.stopped = false
57
59
  this.disposeListener = undefined
@@ -174,7 +176,7 @@ export class Gateway {
174
176
  try { chat.abort?.abort?.() } catch { /* safe best-effort abort */ }
175
177
  chat.abort = new AbortController()
176
178
  const run = chat.busy.then(() => this.runTurn(chat, turnInput, chat.abort.signal))
177
- chat.busy = run.catch(() => {})
179
+ chat.busy = run.catch((e) => { void e })
178
180
  run.catch((err) => {
179
181
  const msg = err instanceof Error ? err.message : String(err)
180
182
  this.ctx.logger?.warn?.(`dsh-messenger-gateway: cron turn: ${msg}`)
@@ -350,6 +352,7 @@ export class Gateway {
350
352
  if (this.outbox) this.outbox.stop()
351
353
  if (this.scheduler) this.scheduler.stop()
352
354
  if (this.disposeListener) this.disposeListener()
355
+ clearModelCatalogCache()
353
356
  if (this.idleTimer) clearInterval(this.idleTimer)
354
357
  for (const a of this.adapterList) { try { a.stop() } catch (e) { this.logger?.debug?.('adapter stop error:', e?.message || e) } }
355
358
  this.adapterList = []
@@ -360,6 +363,7 @@ export class Gateway {
360
363
  this.sessionToChat.clear()
361
364
  this.sessionToThread.clear()
362
365
  this.threadToSession.clear()
366
+ this.recentSessions.clear()
363
367
  for (const pending of this.pendingAsks.values()) {
364
368
  releaseCallbacks(this.callbackIndex, pending.callbackKeys)
365
369
  rejectPendingAsk(pending, new Error('gateway stopped'))
@@ -554,7 +558,7 @@ export class Gateway {
554
558
  try { chat.abort?.abort?.() } catch { /* safe best-effort abort */ }
555
559
  chat.abort = new AbortController()
556
560
  const run = chat.busy.then(() => this.runTurn(chat, turnInput, chat.abort.signal))
557
- chat.busy = run.catch(() => {})
561
+ chat.busy = run.catch((e) => { void e })
558
562
  // Do NOT await: Telegram poll is sequential; awaiting blocked steer and /stop until the turn finished.
559
563
  run.catch((err) => {
560
564
  const msg = err instanceof Error ? err.message : String(err)
@@ -659,19 +663,35 @@ export class Gateway {
659
663
  const self = this
660
664
  const agents = this.ctx.get?.('agents') || this.ctx.agents
661
665
  const targetSessionId = existingSessionId ? SessionId(existingSessionId) : SessionId(`msgw-${randomUUID()}`)
662
- const handle = await agents.create({
663
- sessionId: targetSessionId,
664
- meta: { cwd },
665
- agentOptions: { provider, model },
666
- setup: (agentCtx) => {
667
- installModelSelection(agentCtx, { current: { provider, model }, assembled: undefined })
668
- if (self.tg().approvalsEnabled !== false) {
669
- agentCtx.on('approval/request', (req, next) => self.answerApproval(key, req, next))
670
- }
671
- },
672
- })
666
+ const setup = (agentCtx) => {
667
+ installModelSelection(agentCtx, { current: { provider, model }, assembled: undefined })
668
+ if (self.tg().approvalsEnabled !== false) {
669
+ agentCtx.on('approval/request', (req, next) => self.answerApproval(key, req, next))
670
+ }
671
+ }
672
+ const handle = existingSessionId
673
+ ? (agents.resume
674
+ ? await agents.resume({
675
+ resumeSessionId: SessionId(existingSessionId),
676
+ agentOptions: { provider, model },
677
+ setup,
678
+ })
679
+ : await agents.create({
680
+ sessionId: targetSessionId,
681
+ meta: { cwd },
682
+ agentOptions: { provider, model },
683
+ setup,
684
+ }))
685
+ : await agents.create({
686
+ sessionId: targetSessionId,
687
+ meta: { cwd },
688
+ agentOptions: { provider, model },
689
+ setup,
690
+ })
673
691
  await handle.agent.whenIdle()
674
- await registerSessionInWorkspace(this.ctx, targetSessionId, cwd, this.ctx.logger).catch(() => {})
692
+ if (!existingSessionId) {
693
+ await registerSessionInWorkspace(this.ctx, targetSessionId, cwd, this.ctx.logger).catch((e) => { this.logger?.debug?.('registerSessionInWorkspace error:', e?.message || e) })
694
+ }
675
695
  // Opt-in: name the session after the chat that opened it, so a bot serving
676
696
  // several chats keeps an unambiguous session list.
677
697
  if (!existingSessionId && agentCfg.sessionTitleFromChat === true) {
package/lib/http.js CHANGED
@@ -72,7 +72,6 @@ export function isPrivateAddress(value) {
72
72
  return false
73
73
  }
74
74
 
75
- export const isLoopbackOrLan = isPrivateAddress
76
75
 
77
76
  export function getConnection(ctx) {
78
77
  try {
@@ -207,6 +206,9 @@ export function isTrustedSettingsRequest(req, expectedSecret, ctx = null) {
207
206
 
208
207
  // 5. Remote caller (LAN RFC 1918 or WAN) without secret and without DSH connection session:
209
208
  // LAN is NOT authentication! Fail-closed (#157).
209
+ if (remote !== undefined && isPrivateAddress(remote)) {
210
+ return false
211
+ }
210
212
  return false
211
213
  }
212
214
 
package/lib/index.js CHANGED
@@ -319,7 +319,7 @@ export function apply(ctx, config) {
319
319
  isReady: () => Boolean(settingsBridge.getSettingsApi()),
320
320
  }
321
321
 
322
- const getGw = () => gateway
322
+ const getGw = () => gateway || ctx.get?.('messenger-gateway')
323
323
 
324
324
  ctx.effect(() => ctx.provide('messenger', createMessengerService(getGw)), 'dsh-messenger-gateway: messenger service')
325
325
 
@@ -412,57 +412,146 @@ export function apply(ctx, config) {
412
412
  }
413
413
  }, 'dsh-messenger-gateway: dynamic skills sync')
414
414
 
415
- // Notify β†’ Telegram home bridge (non-msgw sessions only)
415
+ // Notify β†’ Telegram home bridge (non-msgw sessions only) (#187)
416
416
  ctx.effect(() => {
417
+ const turnStarts = new Map()
418
+ const seenEvents = new Map()
419
+
420
+ const cleanOldEntries = (map, maxAgeMs = 7_200_000, maxEntries = 500) => {
421
+ const now = Date.now()
422
+ if (map.size > maxEntries) {
423
+ for (const [k, ts] of map.entries()) {
424
+ if (now - ts > maxAgeMs) map.delete(k)
425
+ }
426
+ }
427
+ }
428
+
417
429
  const handleNotify = (session, event) => {
418
430
  if (!session || !event) return
419
431
  const cfg = source().telegram?.notifyBridge
420
432
  if (!cfg?.enabled) return
433
+
434
+ const sessionId = String(session.id || '')
435
+ if (!sessionId) return
436
+
437
+ const prefixes = cfg.excludeSessionPrefixes || ['msgw-']
438
+ if (isExcludedSession(sessionId, prefixes)) return
439
+
440
+ const now = Date.now()
441
+
421
442
  if (event.type === 'turn/start') {
422
- const now = Date.now()
423
- if (turnStarts.size > 50) {
424
- for (const [sid, ts] of turnStarts.entries()) {
425
- if (now - ts > 7_200_000) turnStarts.delete(sid)
426
- }
443
+ cleanOldEntries(turnStarts, 7_200_000, 100)
444
+ turnStarts.set(sessionId, now)
445
+ return
446
+ }
447
+
448
+ const configuredEvents = new Set(
449
+ (cfg.events?.length ? cfg.events : ['task_done', 'error'])
450
+ .map((e) => String(e).toLowerCase().replace(/-/g, '_'))
451
+ )
452
+
453
+ let kind = null
454
+ let title = null
455
+ let replayKey = null
456
+ const lines = []
457
+
458
+ if (event.type === 'approval/asked' || event.type === 'approval/request') {
459
+ kind = 'approval'
460
+ title = 'Action approval required'
461
+ const data = event.data || {}
462
+ const reqId = data.id || data.callId || ''
463
+ replayKey = `${sessionId}:approval:${reqId}:${data.toolName || ''}`
464
+ if (!configuredEvents.has('approval')) return
465
+
466
+ lines.push(
467
+ `【${title}】`,
468
+ `session: ${sessionId}`,
469
+ )
470
+ if (data.toolName) lines.push(`tool: ${data.toolName}`)
471
+ if (data.reason) lines.push(`reason: ${data.reason}`)
472
+ if (reqId) lines.push(`id: ${reqId}`)
473
+ } else if (event.type === 'turn/end') {
474
+ const reason = event.data?.reason || event.reason || event.data
475
+ const rawKind = String(reason?.kind || '').toLowerCase().replace(/-/g, '_')
476
+
477
+ if (rawKind === 'completed') {
478
+ kind = 'task_done'
479
+ title = 'Task completed'
480
+ } else if (rawKind === 'blocked') {
481
+ kind = 'blocked'
482
+ title = 'Agent blocked'
483
+ } else if (rawKind === 'max_tokens' || rawKind === 'maxtokens') {
484
+ kind = 'max_tokens'
485
+ title = 'Max tokens reached'
486
+ } else {
487
+ kind = 'error'
488
+ title = 'Agent error'
489
+ }
490
+
491
+ if (!configuredEvents.has(kind)) return
492
+
493
+ const turn = event.data?.turn || event.turn || ''
494
+ replayKey = `${sessionId}:turn_end:${turn}:${kind}`
495
+
496
+ const started = turnStarts.get(sessionId)
497
+ turnStarts.delete(sessionId)
498
+ const dur = started ? Math.round((now - started) / 1000) : null
499
+
500
+ lines.push(
501
+ `【${title}】`,
502
+ `session: ${sessionId}`,
503
+ )
504
+ if (dur != null) lines.push(`duration: ${dur}s`)
505
+
506
+ if (kind === 'error') {
507
+ const err = reason?.error
508
+ lines.push(`error: ${err?.message || err?.code || 'unknown'}`)
509
+ } else if (kind === 'blocked' && reason?.reason) {
510
+ lines.push(`reason: ${reason.reason}`)
427
511
  }
428
- turnStarts.set(String(session.id), now)
512
+ } else {
429
513
  return
430
514
  }
431
- if (event.type !== 'turn/end') return
432
- const prefixes = cfg.excludeSessionPrefixes || ['msgw-']
433
- if (isExcludedSession(session.id, prefixes)) return
434
- const reason = event.data?.reason || event.reason || event.data
435
- const kind = reason?.kind === 'completed' ? 'task_done' : 'error'
436
- const events = new Set(cfg.events?.length ? cfg.events : ['task_done', 'error'])
437
- if (!events.has(kind)) return
515
+
516
+ // Replay prevention (no duplicate notifications on projection replay)
517
+ cleanOldEntries(seenEvents, 3_600_000, 500)
518
+ if (replayKey) {
519
+ if (seenEvents.has(replayKey)) return
520
+ seenEvents.set(replayKey, now)
521
+ }
522
+
438
523
  const gw = getGw()
439
524
  if (!gw) return
440
- const started = turnStarts.get(String(session.id))
441
- turnStarts.delete(String(session.id))
442
- const dur = started ? Math.round((Date.now() - started) / 1000) : null
443
- const title = kind === 'task_done' ? 'Task completed' : 'Agent error'
444
- const lines = [
445
- `【${title}】`,
446
- `session: ${session.id}`,
447
- ]
448
- if (dur != null) lines.push(`duration: ${dur}s`)
449
- if (reason?.kind === 'error') {
450
- lines.push(`error: ${reason.error?.message || reason.error?.code || 'unknown'}`)
451
- }
525
+
452
526
  const homeName = cfg.home || 'default'
453
- const home = gw.messenger.home?.() || null
454
- if (home && gw.isMuted?.(home.chatId)) return
455
- gw.messengerSend({ platform: 'telegram', home: homeName }, { text: lines.join('\n') })
456
- .catch((e) => ctx.logger?.warn?.(`notify bridge: ${e.message}`))
527
+ const home = gw.messenger?.home?.(homeName) || gw.messenger?.home?.() || null
528
+ if (!home || !home.chatId) {
529
+ ctx.logger?.debug?.(`notify bridge: recipient home "${homeName}" not found or missing chatId`)
530
+ return
531
+ }
532
+ if (gw.isMuted?.(home.chatId)) return
533
+
534
+ // Non-blocking async dispatch so agent turn is never stalled
535
+ Promise.resolve().then(async () => {
536
+ try {
537
+ await gw.messengerSend({ platform: 'telegram', home: homeName }, { text: lines.join('\n') })
538
+ } catch (e) {
539
+ ctx.logger?.warn?.(`notify bridge delivery failed: ${e?.message || e}`)
540
+ }
541
+ })
457
542
  }
458
543
 
459
544
  const un1 = ctx.on('session/event', handleNotify)
460
545
  const un2 = ctx.on('turn/end', (session, data) => handleNotify(session, { type: 'turn/end', data }))
461
546
  const un3 = ctx.on('turn/start', (session, data) => handleNotify(session, { type: 'turn/start', data }))
547
+ const un4 = ctx.on('approval/asked', (session, data) => handleNotify(session, { type: 'approval/asked', data }))
548
+ const un5 = ctx.on('approval/request', (session, data) => handleNotify(session, { type: 'approval/request', data }))
462
549
  return () => {
463
550
  if (typeof un1 === 'function') un1()
464
551
  if (typeof un2 === 'function') un2()
465
552
  if (typeof un3 === 'function') un3()
553
+ if (typeof un4 === 'function') un4()
554
+ if (typeof un5 === 'function') un5()
466
555
  }
467
556
  }, 'dsh-messenger-gateway: notify bridge')
468
557
 
package/lib/outbound.js CHANGED
@@ -99,7 +99,7 @@ export async function fetchInternalImage(baseUrl, path, signal, opts = {}) {
99
99
  if (done) break
100
100
  total += value.length
101
101
  if (total > maxBytes) {
102
- reader.cancel().catch(() => {})
102
+ reader.cancel().catch((e) => { void e })
103
103
  throw new Error(`image size exceeds limit of ${maxBytes} bytes`)
104
104
  }
105
105
  chunks.push(value)
@@ -16,7 +16,7 @@ export async function writeJsonAtomic(filePath, data) {
16
16
  await writeFile(tmpPath, serialized, 'utf8')
17
17
  await rename(tmpPath, filePath)
18
18
  } catch (err) {
19
- await unlink(tmpPath).catch(() => {})
19
+ await unlink(tmpPath).catch((e) => { void e })
20
20
  throw err
21
21
  }
22
22
  }
package/lib/stream.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { escapeHtml } from './telegram-format.js'
2
+ import { stripReasoningPreamble } from './text.js'
2
3
 
3
4
  /** Helpers for Telegram streaming edits + progress. */
4
5
 
@@ -144,15 +145,16 @@ export function formatReasoningFinal(rawText, deltaReasoning, options = {}) {
144
145
  const thoughtCollapse = options?.thoughtCollapse !== false
145
146
  const locale = options?.locale || 'en'
146
147
  const parsed = parseReasoningStream(rawText, deltaReasoning)
148
+ const cleanContent = stripReasoningPreamble(parsed.content || rawText)
147
149
 
148
150
  if (!parsed.hasThought || !showReasoning) {
149
- return parsed.content || String(rawText || '')
151
+ return cleanContent
150
152
  }
151
153
 
152
154
  const quoteTag = thoughtCollapse ? '<blockquote expandable>' : '<blockquote>'
153
155
  const thoughtHeader = String(locale).toLowerCase().startsWith('zh') ? '🧠 <i>思考过程:</i>' : '🧠 <i>Thought process:</i>'
154
156
  const thoughtBlock = `${quoteTag}${thoughtHeader}\n${escapeHtml(parsed.thought)}</blockquote>\n\n`
155
- return `${thoughtBlock}${parsed.content}`
157
+ return `${thoughtBlock}${cleanContent}`
156
158
  }
157
159
 
158
160
  export function parseRetryAfter(err) {
package/lib/tts.js CHANGED
@@ -89,7 +89,7 @@ export async function convertToOggOpus(audioBytes, inputMime = 'audio/mpeg') {
89
89
  ])
90
90
  return await readFile(output)
91
91
  } finally {
92
- await rm(dir, { recursive: true, force: true }).catch(() => {})
92
+ await rm(dir, { recursive: true, force: true }).catch((e) => { void e })
93
93
  }
94
94
  }
95
95
 
package/lib/workspace.js CHANGED
@@ -150,12 +150,6 @@ export async function registerSessionInWorkspace(ctx, sessionId, cwd, logger) {
150
150
  }
151
151
  import { writeJsonAtomicSync } from "./storage-atomic.js"
152
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
153
  export function inspectGitWorkspace(dirPath) {
160
154
  try {
161
155
  const gitPath = path.join(dirPath, ".git")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-messenger-gateway",
3
- "version": "0.4.31",
3
+ "version": "0.4.33",
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",
@@ -35,8 +35,9 @@
35
35
  "scripts": {
36
36
  "test": "node --test test/*.test.mjs",
37
37
  "test:load": "node scripts/verify-dsh-load.mjs",
38
- "test:all": "npm test && npm run test:load",
39
- "smoke:http": "node scripts/smoke-http.mjs"
38
+ "test:all": "npm test && npm run test:load && npm run pack:check",
39
+ "smoke:http": "node scripts/smoke-http.mjs",
40
+ "pack:check": "node scripts/pack-check.mjs"
40
41
  },
41
42
  "dsh": {
42
43
  "bundle": {
@@ -67,5 +68,9 @@
67
68
  },
68
69
  "bugs": {
69
70
  "url": "https://github.com/GooDAnDReaDY/dsh-messenger-gateway/issues"
71
+ },
72
+ "overrides": {
73
+ "zod": "^4.6.6",
74
+ "fast-uri": "^3.1.9"
70
75
  }
71
76
  }