@goodandready/dsh-messenger-gateway 0.4.32 → 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.
@@ -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'
@@ -103,7 +104,7 @@ export async function listFiles(baseCwd, subPath = '.', opts = {}) {
103
104
  isDirectory: false,
104
105
  currentPath: relativePath,
105
106
  entries: [{ name: relativePath, size: st.size, isDirectory: false }],
106
- 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>`,
107
108
  }
108
109
  }
109
110
 
@@ -153,9 +154,9 @@ export async function listFiles(baseCwd, subPath = '.', opts = {}) {
153
154
 
154
155
  for (const e of sliced) {
155
156
  if (e.isDirectory) {
156
- lines.push(`📁 <code>${e.name}/</code>`)
157
+ lines.push(`📁 <code>${escapeHtml(e.name)}/</code>`)
157
158
  } else {
158
- lines.push(`📄 <code>${e.name}</code> (${formatFileSize(e.size)})`)
159
+ lines.push(`📄 <code>${escapeHtml(e.name)}</code> (${formatFileSize(e.size)})`)
159
160
  }
160
161
  }
161
162
 
@@ -245,7 +246,7 @@ export async function handleGetCommand(agentCwd, targetRel, maxDocBytes = 50 * 1
245
246
  dataBase64: res.bytes.toString('base64'),
246
247
  }
247
248
  return {
248
- text: `📄 File: <b>${res.name}</b> (${formatFileSize(res.size)})`,
249
+ text: `📄 File: <b>${escapeHtml(res.name)}</b> (${formatFileSize(res.size)})`,
249
250
  files: [file],
250
251
  }
251
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) {
@@ -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'))
@@ -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)' })
package/lib/gateway.js CHANGED
@@ -53,6 +53,7 @@ export class Gateway {
53
53
  this.pendingAsks = new Map()
54
54
  this.adapters = new Map()
55
55
  this.adapterList = []
56
+ this.recentSessions = new Map()
56
57
  // true после stop(): start() обязан прекратить работу, если его обогнали.
57
58
  this.stopped = false
58
59
  this.disposeListener = undefined
@@ -362,6 +363,7 @@ export class Gateway {
362
363
  this.sessionToChat.clear()
363
364
  this.sessionToThread.clear()
364
365
  this.threadToSession.clear()
366
+ this.recentSessions.clear()
365
367
  for (const pending of this.pendingAsks.values()) {
366
368
  releaseCallbacks(this.callbackIndex, pending.callbackKeys)
367
369
  rejectPendingAsk(pending, new Error('gateway stopped'))
@@ -661,19 +663,35 @@ export class Gateway {
661
663
  const self = this
662
664
  const agents = this.ctx.get?.('agents') || this.ctx.agents
663
665
  const targetSessionId = existingSessionId ? SessionId(existingSessionId) : SessionId(`msgw-${randomUUID()}`)
664
- const handle = await agents.create({
665
- sessionId: targetSessionId,
666
- meta: { cwd },
667
- agentOptions: { provider, model },
668
- setup: (agentCtx) => {
669
- installModelSelection(agentCtx, { current: { provider, model }, assembled: undefined })
670
- if (self.tg().approvalsEnabled !== false) {
671
- agentCtx.on('approval/request', (req, next) => self.answerApproval(key, req, next))
672
- }
673
- },
674
- })
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
+ })
675
691
  await handle.agent.whenIdle()
676
- await registerSessionInWorkspace(this.ctx, targetSessionId, cwd, this.ctx.logger).catch((e) => { this.logger?.debug?.('registerSessionInWorkspace error:', e?.message || e) })
692
+ if (!existingSessionId) {
693
+ await registerSessionInWorkspace(this.ctx, targetSessionId, cwd, this.ctx.logger).catch((e) => { this.logger?.debug?.('registerSessionInWorkspace error:', e?.message || e) })
694
+ }
677
695
  // Opt-in: name the session after the chat that opened it, so a bot serving
678
696
  // several chats keeps an unambiguous session list.
679
697
  if (!existingSessionId && agentCfg.sessionTitleFromChat === true) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-messenger-gateway",
3
- "version": "0.4.32",
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",