@goodandready/dsh-messenger-gateway 0.4.31 β†’ 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.
@@ -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) {
@@ -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 = [
@@ -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}`)
@@ -350,6 +351,7 @@ export class Gateway {
350
351
  if (this.outbox) this.outbox.stop()
351
352
  if (this.scheduler) this.scheduler.stop()
352
353
  if (this.disposeListener) this.disposeListener()
354
+ clearModelCatalogCache()
353
355
  if (this.idleTimer) clearInterval(this.idleTimer)
354
356
  for (const a of this.adapterList) { try { a.stop() } catch (e) { this.logger?.debug?.('adapter stop error:', e?.message || e) } }
355
357
  this.adapterList = []
@@ -554,7 +556,7 @@ export class Gateway {
554
556
  try { chat.abort?.abort?.() } catch { /* safe best-effort abort */ }
555
557
  chat.abort = new AbortController()
556
558
  const run = chat.busy.then(() => this.runTurn(chat, turnInput, chat.abort.signal))
557
- chat.busy = run.catch(() => {})
559
+ chat.busy = run.catch((e) => { void e })
558
560
  // Do NOT await: Telegram poll is sequential; awaiting blocked steer and /stop until the turn finished.
559
561
  run.catch((err) => {
560
562
  const msg = err instanceof Error ? err.message : String(err)
@@ -671,7 +673,7 @@ export class Gateway {
671
673
  },
672
674
  })
673
675
  await handle.agent.whenIdle()
674
- 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) })
675
677
  // Opt-in: name the session after the chat that opened it, so a bot serving
676
678
  // several chats keeps an unambiguous session list.
677
679
  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.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
  }