@goodandready/dsh-messenger-gateway 0.4.30 → 0.4.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -48,7 +48,8 @@ Talk to your Harness agent from Telegram: text, voice, photos, documents, inline
48
48
  - Configurable proxy support: HTTP, HTTPS, SOCKS5, and SOCKS5h (`telegram.proxyUrl`)
49
49
  - Custom Bot API root URL (`telegram.apiRoot`) for reverse proxies and local Bot API servers
50
50
  - Multi-transport support: Telegram, Discord (Webhooks & Bot API), and Slack (Webhooks & Bot API)
51
- - Allowlist + pairing codes
51
+ - Allowlist + pairing codes (with configurable `allowlistMode`: `open` | `closed`)
52
+ - Conversation switching directly from chat (`/sessions` and `/resume <n|id>`)
52
53
  - Per-user or per-chat sessions (`sessionScope`)
53
54
  - Forum topics as separate sessions
54
55
  - Named sessions from chat metadata (`agent.sessionTitleFromChat`: `TG · @username` or `TG · Group › topic N`)
@@ -105,6 +106,8 @@ Spoken replies use Telegram `sendVoice`. If TTS returns MP3 (or other non-Opus a
105
106
  | `/start` `/help` | Help |
106
107
  | `/whoami` | Your Telegram user id |
107
108
  | `/new` | New agent session |
109
+ | `/sessions` | List recent messenger conversations |
110
+ | `/resume <n|id>` | Switch chat to previous session |
108
111
  | `/stop` | Abort the current turn |
109
112
  | `/model` | Interactive 2-step model picker (providers → models) or `/model <prov> <mod>` |
110
113
  | `/status` | Gateway status and session counters |
@@ -140,6 +143,8 @@ In addition to Telegram, outbound messages can be dispatched to Discord and Slac
140
143
  ## Configuration notes
141
144
 
142
145
  - `sessionScope`: `user` (default) or `chat` — how group chats isolate sessions
146
+ - `allowlistMode`: `open` (default) or `closed` — in `closed` mode, an empty allowlist admits nobody (fail-closed)
147
+ - `sessionList`: `true` (default) — enables `/sessions` and `/resume` commands in chat
143
148
  - `sessionTitleFromChat`: `false` (default) — name each new session after its originating chat (`TG · @user`, `TG · Group › topic N`) instead of generic generated titles
144
149
  - `voiceMode`: `mirror` / `always` / `off` — when to speak replies (also `/voice`)
145
150
  - `tts.enabled` / `tts.maxChars` — TTS gate and length cap
@@ -10,6 +10,7 @@ export default function createAdapters(deps) {
10
10
  list.push(new TelegramAdapter({
11
11
  botToken: tg.botToken,
12
12
  allowedUserIds: tg.allowedUserIds,
13
+ allowlistMode: tg.allowlistMode || 'open',
13
14
  timeoutSeconds: tg.pollTimeoutSeconds,
14
15
  pollIntervalMs: tg.pollIntervalMs,
15
16
  commands: tg.commands,
@@ -40,6 +40,7 @@ export class TelegramAdapter {
40
40
  this.name = 'telegram'
41
41
  this.token = String(opts.botToken || '').trim()
42
42
  this.allowedUserIds = (opts.allowedUserIds || []).map(Number).filter((n) => Number.isFinite(n))
43
+ this.allowlistMode = opts.allowlistMode === 'closed' ? 'closed' : 'open'
43
44
  this.timeoutSeconds = Number(opts.timeoutSeconds) || 50
44
45
  this.pollIntervalMs = Number(opts.pollIntervalMs) || 500
45
46
  this.media = opts.media || {}
@@ -325,7 +326,7 @@ export class TelegramAdapter {
325
326
  callback_query_id: update.callback_query.id,
326
327
  text: 'Access denied',
327
328
  show_alert: true,
328
- }).catch(() => {})
329
+ }).catch((e) => { this.logger?.debug?.('answerCallbackQuery access denied failed:', e?.message || e) })
329
330
  return
330
331
  }
331
332
  try { await this.onCallback?.(this.wrapCallback(update.callback_query)) } catch (e) {
@@ -382,6 +383,9 @@ export class TelegramAdapter {
382
383
 
383
384
  allowed(userId) {
384
385
  if (typeof this.isUserAllowed === 'function') return this.isUserAllowed(userId)
386
+ if (this.allowlistMode === 'closed') {
387
+ return this.allowedUserIds.length > 0 && this.allowedUserIds.includes(Number(userId))
388
+ }
385
389
  return this.allowedUserIds.length === 0 || this.allowedUserIds.includes(Number(userId))
386
390
  }
387
391
 
package/lib/commands.js CHANGED
@@ -3,6 +3,8 @@ export const DEFAULT_TELEGRAM_COMMANDS = [
3
3
  { command: 'start', description: 'Connect and show greeting' },
4
4
  { command: 'help', description: 'Show commands help' },
5
5
  { command: 'new', description: 'Start a new agent session' },
6
+ { command: 'sessions', description: 'List recent messenger sessions' },
7
+ { command: 'resume', description: 'Resume session: /resume <n|id>' },
6
8
  { command: 'whoami', description: 'Show your messenger user ID' },
7
9
  { command: 'stop', description: 'Interrupt current turn' },
8
10
  { command: 'pair', description: 'Approve pairing code: /pair CODE' },
@@ -101,6 +103,8 @@ export const HELP_TEXT = [
101
103
  '💬 <b>Session & Chat:</b>',
102
104
  '• /help — show this command reference',
103
105
  '• /new — start fresh session',
106
+ '• /sessions — list recent conversations',
107
+ '• /resume <n|id> — resume previous session',
104
108
  '• /stop — interrupt current response',
105
109
  '• /model — interactive model selector (/model list)',
106
110
  '• /role [name] — switch persona or role (/role list)',
package/lib/config.js CHANGED
@@ -22,6 +22,8 @@ export const PluginConfig = z.object({
22
22
  enabled: z.boolean().default(false),
23
23
  botToken: z.string().role('secret').default(''),
24
24
  allowedUserIds: z.array(z.number()).default([]),
25
+ allowlistMode: z.union([z.const('open'), z.const('closed')]).default('open')
26
+ .description('Allowlist mode: open admits all users when list is empty; closed refuses unknown users when list is empty'),
25
27
  pollTimeoutSeconds: z.number().default(50),
26
28
  pollIntervalMs: z.number().default(500),
27
29
  commands: z.array(z.object({
@@ -129,6 +131,8 @@ export const PluginConfig = z.object({
129
131
  .description('In groups: user = per-user session; chat = shared session for the chat/topic'),
130
132
  sessionTitleFromChat: z.boolean().default(false)
131
133
  .description('Name each new session after its chat (TG · @user, TG · Group › topic N) instead of leaving the generated title'),
134
+ sessionList: z.boolean().default(true)
135
+ .description('Enable /sessions and /resume commands to list and switch between recent conversations'),
132
136
  }).volatile(),
133
137
  })
134
138
 
@@ -87,7 +87,8 @@ export function resolveInside(base, candidate = '.') {
87
87
 
88
88
  export async function listFiles(baseCwd, subPath = '.', opts = {}) {
89
89
  const { maxEntries = 50, showHidden = false } = opts
90
- const { base, target, relativePath } = resolveSafePath(baseCwd, subPath)
90
+ const target = resolveInside(baseCwd, subPath)
91
+ const { relativePath } = resolveSafePath(baseCwd, subPath)
91
92
 
92
93
  let st
93
94
  try {
@@ -175,7 +176,8 @@ export async function listFiles(baseCwd, subPath = '.', opts = {}) {
175
176
  }
176
177
 
177
178
  export async function getFileForDownload(baseCwd, relativePath, maxBytes = 50 * 1024 * 1024) {
178
- const { target, relativePath: safeRel } = resolveSafePath(baseCwd, relativePath)
179
+ const target = resolveInside(baseCwd, relativePath)
180
+ const { relativePath: safeRel } = resolveSafePath(baseCwd, relativePath)
179
181
  let st
180
182
  try {
181
183
  st = await stat(target)
@@ -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 = [
@@ -496,6 +496,115 @@ export async function handleGatewayCommand(gw, key, text, input) {
496
496
  }
497
497
 
498
498
 
499
+
500
+ if (cmd === '/sessions') {
501
+ if (gw.config.agent?.sessionList === false) {
502
+ return reply('Session switching is disabled by configuration.')
503
+ }
504
+ const sessionQuery = gw.ctx.get?.('sessionQuery') ?? gw.ctx.sessionQuery
505
+ if (!sessionQuery?.listSessions) {
506
+ return reply('Session listing service is not available on this host.')
507
+ }
508
+ try {
509
+ const records = await sessionQuery.listSessions()
510
+ const filtered = (records || [])
511
+ .filter((r) => {
512
+ const id = String(r?.header?.id || '')
513
+ return id.startsWith('msgw-') && !r?.header?.archived
514
+ })
515
+ .slice(0, 10)
516
+ if (filtered.length === 0) {
517
+ return reply('No recent messenger sessions found.')
518
+ }
519
+ const items = await Promise.all(
520
+ filtered.map(async (r) => {
521
+ const id = r.header.id
522
+ let title = ''
523
+ try {
524
+ const titleSnap = await sessionQuery.readTitle(id)
525
+ title = titleSnap?.title || titleSnap?.value || ''
526
+ } catch { /* best effort */ }
527
+ if (!title) title = r.header.title || id
528
+ const cwd = r.header.cwd || r.header.meta?.cwd || ''
529
+ const dir = cwd ? cwd.split(/[\\/]/).filter(Boolean).slice(-2).join('/') : ''
530
+ return { id, title, dir }
531
+ })
532
+ )
533
+ gw.recentSessions.set(key, items)
534
+ const lines = ['📋 <b>Recent Sessions:</b>', '']
535
+ 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
+ })
539
+ lines.push('', 'Switch using <code>/resume &lt;number&gt;</code>')
540
+ return reply(lines.join('\n'))
541
+ } catch (err) {
542
+ gw.logger?.warn?.(`/sessions failed: ${err?.message || err}`)
543
+ return reply(`Failed to list sessions: ${err?.message || err}`)
544
+ }
545
+ }
546
+
547
+ if (cmd === '/resume') {
548
+ if (gw.config.agent?.sessionList === false) {
549
+ return reply('Session switching is disabled by configuration.')
550
+ }
551
+ const chat = gw.chats.get(key)
552
+ if (chat?.turnActive) {
553
+ return reply('Cannot switch session while a turn is in progress. Use /stop first.')
554
+ }
555
+ const rawArg = text.replace(/^\/resume(?:\s+|$)/i, '').trim()
556
+ if (!rawArg) {
557
+ return reply('Usage: /resume <number> or /resume <sessionId>\nUse /sessions to list available conversations.')
558
+ }
559
+ let targetSessionId = ''
560
+ const num = parseInt(rawArg, 10)
561
+ if (Number.isFinite(num) && num >= 1) {
562
+ const items = gw.recentSessions?.get(key) || []
563
+ const chosen = items[num - 1]
564
+ if (!chosen) {
565
+ return reply(`Session number ${num} not found. Run /sessions first to view the numbered list.`)
566
+ }
567
+ targetSessionId = chosen.id
568
+ } else if (rawArg.startsWith('msgw-')) {
569
+ targetSessionId = rawArg
570
+ } else {
571
+ return reply(`Invalid session reference "${rawArg}". Provide a number from /sessions or a session ID starting with msgw-.`)
572
+ }
573
+
574
+ const currentId = String(chat?.agent?.session?.id || '')
575
+ if (currentId === targetSessionId) {
576
+ return reply(`Already connected to session ${targetSessionId}.`)
577
+ }
578
+
579
+ if (chat) {
580
+ if (chat.abort) chat.abort.abort()
581
+ chat.pendingMedia = []
582
+ gw.chats.delete(key)
583
+ if (currentId) {
584
+ gw.sessionToChat.delete(currentId)
585
+ gw.sessionToThread.delete(currentId)
586
+ }
587
+ const target = chat.target || {}
588
+ gw.threadToSession.delete(`${target.chatId ?? input.chatId}:${target.threadId ?? input.threadId ?? 0}`)
589
+ setImmediate(() => {
590
+ try {
591
+ chat.dispose?.().catch?.((e) => gw.logger?.warn?.(`/resume dispose: ${e?.message || e}`))
592
+ } catch (e) {
593
+ gw.logger?.warn?.(`/resume dispose: ${e?.message || e}`)
594
+ }
595
+ })
596
+ }
597
+
598
+ try {
599
+ const newChat = await gw.createChat(key, input, targetSessionId)
600
+ gw.chats.set(key, newChat)
601
+ return reply(`Resumed session: ${targetSessionId}`)
602
+ } catch (err) {
603
+ gw.logger?.warn?.(`/resume createChat failed: ${err?.message || err}`)
604
+ return reply(`Failed to resume session ${targetSessionId}: ${err?.message || err}`)
605
+ }
606
+ }
607
+
499
608
  if (cmd === '/new') {
500
609
  const chat = gw.chats.get(key)
501
610
  if (!chat) return reply(t('msg.no_active_session', {}, locale))
@@ -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'
@@ -298,14 +298,11 @@ export async function runGatewayTurn(gw, chat, input, signal) {
298
298
  progress = null
299
299
  if (typeof react === 'function') react('').catch?.((e) => { gw.logger?.debug?.('react clear error:', e?.message || e) })
300
300
  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
- }
301
+ const rawAnswer = formatReasoningFinal(rawText, collector.reasoningText, {
302
+ showReasoning: tg.showReasoning !== false,
303
+ thoughtCollapse: tg.thoughtCollapse !== false,
304
+ locale: gw.resolveLocale(input),
305
+ })
309
306
  const processed = await processDiagramsAndTablesAsync(rawAnswer, {
310
307
  artifactPreviews: gw.tg().artifactPreviews !== false,
311
308
  artifactStore: gw.artifactStore,
@@ -399,7 +396,7 @@ export async function runGatewayTurn(gw, chat, input, signal) {
399
396
  gw.sendAlert('status', {
400
397
  title: 'Budget Alert',
401
398
  details: `${warning.message} (Chat: ${input.chatId})`,
402
- }).catch(() => {})
399
+ }).catch((e) => { gw.logger?.debug?.('budgetAlert send error:', e?.message || e) })
403
400
  }
404
401
  }
405
402
  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'
@@ -174,7 +175,7 @@ export class Gateway {
174
175
  try { chat.abort?.abort?.() } catch { /* safe best-effort abort */ }
175
176
  chat.abort = new AbortController()
176
177
  const run = chat.busy.then(() => this.runTurn(chat, turnInput, chat.abort.signal))
177
- chat.busy = run.catch(() => {})
178
+ chat.busy = run.catch((e) => { void e })
178
179
  run.catch((err) => {
179
180
  const msg = err instanceof Error ? err.message : String(err)
180
181
  this.ctx.logger?.warn?.(`dsh-messenger-gateway: cron turn: ${msg}`)
@@ -201,6 +202,10 @@ export class Gateway {
201
202
 
202
203
  isUserAllowed(userId) {
203
204
  const ids = this.effectiveAllowedIds()
205
+ const mode = this.tg()?.allowlistMode || 'open'
206
+ if (mode === 'closed') {
207
+ return ids.length > 0 && ids.includes(Number(userId))
208
+ }
204
209
  return ids.length === 0 || ids.includes(Number(userId))
205
210
  }
206
211
 
@@ -300,6 +305,9 @@ export class Gateway {
300
305
  this.adapterList = this.adapterList.filter((item) => item !== adapter)
301
306
  if (this.tgAdapter === adapter) this.tgAdapter = undefined
302
307
  }
308
+ if ((this.tg()?.allowlistMode || 'open') === 'open' && this.effectiveAllowedIds().length === 0) {
309
+ this.ctx.logger?.warn?.('[dsh-messenger-gateway] telegram allowlist is empty in "open" mode: the bot will accept messages from any Telegram user.')
310
+ }
303
311
  for (const adapter of adapters) {
304
312
  // Регистрируем адаптер ДО `await adapter.start()`: старт адаптера — это
305
313
  // сетевые вызовы (getMe/setMyCommands/deleteWebhook), и если за это время
@@ -343,6 +351,7 @@ export class Gateway {
343
351
  if (this.outbox) this.outbox.stop()
344
352
  if (this.scheduler) this.scheduler.stop()
345
353
  if (this.disposeListener) this.disposeListener()
354
+ clearModelCatalogCache()
346
355
  if (this.idleTimer) clearInterval(this.idleTimer)
347
356
  for (const a of this.adapterList) { try { a.stop() } catch (e) { this.logger?.debug?.('adapter stop error:', e?.message || e) } }
348
357
  this.adapterList = []
@@ -547,7 +556,7 @@ export class Gateway {
547
556
  try { chat.abort?.abort?.() } catch { /* safe best-effort abort */ }
548
557
  chat.abort = new AbortController()
549
558
  const run = chat.busy.then(() => this.runTurn(chat, turnInput, chat.abort.signal))
550
- chat.busy = run.catch(() => {})
559
+ chat.busy = run.catch((e) => { void e })
551
560
  // Do NOT await: Telegram poll is sequential; awaiting blocked steer and /stop until the turn finished.
552
561
  run.catch((err) => {
553
562
  const msg = err instanceof Error ? err.message : String(err)
@@ -664,10 +673,10 @@ export class Gateway {
664
673
  },
665
674
  })
666
675
  await handle.agent.whenIdle()
667
- await registerSessionInWorkspace(this.ctx, targetSessionId, cwd, this.ctx.logger).catch(() => {})
676
+ await registerSessionInWorkspace(this.ctx, targetSessionId, cwd, this.ctx.logger).catch((e) => { this.logger?.debug?.('registerSessionInWorkspace error:', e?.message || e) })
668
677
  // Opt-in: name the session after the chat that opened it, so a bot serving
669
678
  // several chats keeps an unambiguous session list.
670
- if (agentCfg.sessionTitleFromChat === true) {
679
+ if (!existingSessionId && agentCfg.sessionTitleFromChat === true) {
671
680
  try {
672
681
  const titleService = this.ctx.get?.('sessionTitle') ?? this.ctx.sessionTitle
673
682
  const label = chatLabel({
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.30",
3
+ "version": "0.4.32",
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
  }