@goodandready/dsh-messenger-gateway 0.4.29 → 0.4.30

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
@@ -51,6 +51,7 @@ Talk to your Harness agent from Telegram: text, voice, photos, documents, inline
51
51
  - Allowlist + pairing codes
52
52
  - Per-user or per-chat sessions (`sessionScope`)
53
53
  - Forum topics as separate sessions
54
+ - Named sessions from chat metadata (`agent.sessionTitleFromChat`: `TG · @username` or `TG · Group › topic N`)
54
55
  - Quick actions reply keyboard (`/keyboard on|off`)
55
56
  - Multi-select interactive ask forms with checkboxes and pagination (`messenger_ask`)
56
57
  - Artifact & Mermaid diagram rendering (SVG cards) and monospace table formatting
@@ -139,6 +140,7 @@ In addition to Telegram, outbound messages can be dispatched to Discord and Slac
139
140
  ## Configuration notes
140
141
 
141
142
  - `sessionScope`: `user` (default) or `chat` — how group chats isolate sessions
143
+ - `sessionTitleFromChat`: `false` (default) — name each new session after its originating chat (`TG · @user`, `TG · Group › topic N`) instead of generic generated titles
142
144
  - `voiceMode`: `mirror` / `always` / `off` — when to speak replies (also `/voice`)
143
145
  - `tts.enabled` / `tts.maxChars` — TTS gate and length cap
144
146
  - `notifyBridge` — forward non-messenger web session events to a home
@@ -93,14 +93,21 @@ export class TelegramAdapter {
93
93
  this.allowedUserIds = (ids || []).map(Number).filter((n) => Number.isFinite(n))
94
94
  }
95
95
 
96
- async call(method, params = {}) {
96
+ async call(method, params = {}, externalSignal) {
97
97
  const timeoutMs = (this.timeoutSeconds * 1000) + 15000
98
+ // A long poll holds its request open for `timeoutSeconds`, so stopping the
99
+ // adapter has to cancel it: otherwise a reloaded instance keeps processing
100
+ // updates with the code that is already gone.
101
+ const timeoutSignal = AbortSignal.timeout(timeoutMs)
102
+ const signal = externalSignal && typeof AbortSignal.any === 'function'
103
+ ? AbortSignal.any([timeoutSignal, externalSignal])
104
+ : externalSignal || timeoutSignal
98
105
  const fetchOpts = {
99
106
  method: 'POST',
100
107
  headers: { 'Content-Type': 'application/json' },
101
108
  body: JSON.stringify(params),
102
109
  keepalive: true,
103
- signal: AbortSignal.timeout(timeoutMs),
110
+ signal,
104
111
  }
105
112
  const res = await this.apiFetch(`${this.apiRoot}/bot${this.token}/${method}`, fetchOpts)
106
113
  const json = await res.json().catch(() => ({}))
@@ -252,6 +259,7 @@ export class TelegramAdapter {
252
259
 
253
260
  stop() {
254
261
  this.stopped = true
262
+ try { this.pollAbort?.abort() } catch { /* best effort */ }
255
263
  if (this.mediaGroups) {
256
264
  for (const group of this.mediaGroups.values()) {
257
265
  if (group.timeout) clearTimeout(group.timeout)
@@ -273,13 +281,15 @@ export class TelegramAdapter {
273
281
 
274
282
  async poll() {
275
283
  if (this.stopped) return
284
+ this.pollAbort = new AbortController()
285
+ const signal = this.pollAbort.signal
276
286
  let backoffDelay
277
287
  try {
278
288
  const updates = await this.call('getUpdates', {
279
289
  timeout: this.timeoutSeconds,
280
290
  offset: this.offset,
281
291
  allowed_updates: ['message', 'callback_query'],
282
- })
292
+ }, signal)
283
293
  this.pollingConflict = false
284
294
  this.pollErrorCount = 0
285
295
  for (const update of updates || []) {
@@ -515,6 +525,9 @@ export class TelegramAdapter {
515
525
 
516
526
  await this.onMessage({
517
527
  platform: 'telegram', chatId, userId, threadId, chatType, text,
528
+ chatTitle: primaryMsg.chat?.title,
529
+ userName: [primaryMsg.from?.first_name, primaryMsg.from?.last_name].filter(Boolean).join(' '),
530
+ userUsername: primaryMsg.from?.username,
518
531
  attachments: allAttachments, replyText,
519
532
  messageId, reply, typing, startStream, startProgress, react,
520
533
  })
@@ -583,6 +596,9 @@ export class TelegramAdapter {
583
596
 
584
597
  await this.onMessage({
585
598
  platform: 'telegram', chatId, userId, threadId, chatType, text, attachments, replyText,
599
+ chatTitle: msg.chat?.title,
600
+ userName: [msg.from?.first_name, msg.from?.last_name].filter(Boolean).join(' '),
601
+ userUsername: msg.from?.username,
586
602
  messageId, reply, typing, startStream, startProgress, react,
587
603
  })
588
604
  }
package/lib/config.js CHANGED
@@ -127,6 +127,8 @@ export const PluginConfig = z.object({
127
127
  photoOnlyMode: z.union([z.const('prompt'), z.const('run')]).default('prompt'),
128
128
  sessionScope: z.union([z.const('chat'), z.const('user')]).default('user')
129
129
  .description('In groups: user = per-user session; chat = shared session for the chat/topic'),
130
+ sessionTitleFromChat: z.boolean().default(false)
131
+ .description('Name each new session after its chat (TG · @user, TG · Group › topic N) instead of leaving the generated title'),
130
132
  }).volatile(),
131
133
  })
132
134
 
@@ -498,15 +498,33 @@ export async function handleGatewayCommand(gw, key, text, input) {
498
498
 
499
499
  if (cmd === '/new') {
500
500
  const chat = gw.chats.get(key)
501
- if (chat) {
502
- if (chat.abort) chat.abort.abort()
503
- chat.pendingMedia = []
504
- gw.sessionToChat.delete(String(chat.agent.session.id))
505
- gw.chats.delete(key)
506
- await chat.dispose()
507
- return reply('Session reset.')
508
- }
509
- return reply(t('msg.no_active_session', {}, locale))
501
+ if (!chat) return reply(t('msg.no_active_session', {}, locale))
502
+ if (chat.abort) chat.abort.abort()
503
+ chat.pendingMedia = []
504
+ const sessionId = String(chat.agent?.session?.id || '')
505
+ // Detach every mapping before disposing. A surviving `threadToSession` (or
506
+ // `sessionToThread`) entry makes the next inbound message resume the very
507
+ // session that is being torn down, which DSH rejects with
508
+ // "cannot append outside a SessionStore" / "cannot create effect on an
509
+ // inactive context".
510
+ gw.chats.delete(key)
511
+ if (sessionId) {
512
+ gw.sessionToChat.delete(sessionId)
513
+ gw.sessionToThread.delete(sessionId)
514
+ }
515
+ const target = chat.target || {}
516
+ gw.threadToSession.delete(`${target.chatId ?? input.chatId}:${target.threadId ?? input.threadId ?? 0}`)
517
+ // Dispose out of band: abort() just fired, and awaiting the teardown in the
518
+ // same tick lets the draining turn append a closing event after the store
519
+ // closed. The command reply must not wait for that drain either.
520
+ setImmediate(() => {
521
+ try {
522
+ chat.dispose?.().catch?.((err) => gw.logger?.warn?.(`/new dispose: ${err?.message || err}`))
523
+ } catch (err) {
524
+ gw.logger?.warn?.(`/new dispose: ${err?.message || err}`)
525
+ }
526
+ })
527
+ return reply('Session reset.')
510
528
  }
511
529
 
512
530
  if (cmd === '/whoami') {
package/lib/gateway.js CHANGED
@@ -31,6 +31,7 @@ import {
31
31
  } from './forum-mirror.js'
32
32
  import { resolveInternalBaseUrl } from './config.js'
33
33
  import { resolveEffectiveCwd, registerSessionInWorkspace, createTopicWorkspaceStore, getCwdWarning } from './workspace.js'
34
+ import { chatLabel } from './labels.js'
34
35
  import { createOutboxQueue, resolveOutboxStoragePath } from './outbox.js'
35
36
  import { realpathSync } from 'node:fs'
36
37
  import { resolve } from 'node:path'
@@ -664,6 +665,24 @@ export class Gateway {
664
665
  })
665
666
  await handle.agent.whenIdle()
666
667
  await registerSessionInWorkspace(this.ctx, targetSessionId, cwd, this.ctx.logger).catch(() => {})
668
+ // Opt-in: name the session after the chat that opened it, so a bot serving
669
+ // several chats keeps an unambiguous session list.
670
+ if (agentCfg.sessionTitleFromChat === true) {
671
+ try {
672
+ const titleService = this.ctx.get?.('sessionTitle') ?? this.ctx.sessionTitle
673
+ const label = chatLabel({
674
+ platform: input?.platform,
675
+ chatType: input?.chatType,
676
+ chatTitle: input?.chatTitle,
677
+ threadId: input?.threadId || 0,
678
+ userName: input?.userName,
679
+ userUsername: input?.userUsername,
680
+ })
681
+ if (titleService?.rename && label) titleService.rename(handle.agent.session, label)
682
+ } catch (err) {
683
+ this.ctx.logger?.warn?.(`[dsh-messenger-gateway] session title rename failed: ${err?.message || err}`)
684
+ }
685
+ }
667
686
  const chat = {
668
687
  key, agent: handle.agent, dispose: handle.dispose, busy: Promise.resolve(),
669
688
  lastUsed: Date.now(), abort: undefined, pendingMedia: [], turnActive: false,
package/lib/index.js CHANGED
@@ -699,9 +699,18 @@ export function apply(ctx, config) {
699
699
  endpoint: '/dsh-messenger-gateway/update',
700
700
  }), 'dsh-messenger-gateway: plugin updater')
701
701
 
702
- ctx.on('dispose', () => {
703
- if (gateway) gateway.stop()
702
+ // Cordis never delivers a 'dispose' event to `ctx.on`, so this cleanup never
703
+ // ran: every plugin reload left the previous gateway alive, and its Telegram
704
+ // long poll kept consuming updates with the stale code while the fresh
705
+ // instance fought it for getUpdates. Registering the teardown as an effect
706
+ // makes the old gateway stop when the plugin is reloaded or disposed.
707
+ ctx.effect(() => () => {
708
+ try {
709
+ if (gateway) gateway.stop()
710
+ } catch (err) {
711
+ ctx.logger?.warn?.(`[dsh-messenger-gateway] gateway stop on dispose failed: ${err?.message || err}`)
712
+ }
704
713
  if (typeof webhookRouteDispose === 'function') webhookRouteDispose()
705
- })
714
+ }, 'dsh-messenger-gateway: stop gateway')
706
715
  sync()
707
716
  }
package/lib/labels.js ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Human-readable session titles built from the originating chat.
3
+ *
4
+ * A messenger session is otherwise titled by DSH's own generator, which only sees
5
+ * the message text and cannot tell two chats apart. Labelling the session with
6
+ * "TG · @user" (DM) or "TG · Group › topic N" (group/forum topic) makes the
7
+ * sidebar and the session list unambiguous when one bot serves many chats.
8
+ */
9
+
10
+ const PLATFORM_TAGS = { telegram: 'TG', discord: 'DC', slack: 'SL' }
11
+
12
+ /**
13
+ * Short platform tag used as the title prefix.
14
+ * @param platform - adapter platform id.
15
+ * @returns a 2-3 character tag, e.g. `TG`.
16
+ */
17
+ export function platformTag(platform) {
18
+ const key = String(platform || '').toLowerCase()
19
+ return PLATFORM_TAGS[key] || key.slice(0, 2).toUpperCase() || 'MSG'
20
+ }
21
+
22
+ /**
23
+ * Truncate a string to a UTF-8 byte budget without splitting a code point.
24
+ * @param text - source text.
25
+ * @param maxBytes - byte budget (0/undefined = no limit).
26
+ * @returns the text, or its head plus an ellipsis when it does not fit.
27
+ */
28
+ export function truncateBytes(text, maxBytes) {
29
+ const value = String(text || '')
30
+ if (!maxBytes || Buffer.byteLength(value, 'utf8') <= maxBytes) return value
31
+ // The ellipsis is multi-byte too: reserve its size instead of assuming one byte.
32
+ const budget = maxBytes - Buffer.byteLength('…', 'utf8')
33
+ let out = ''
34
+ for (const char of value) {
35
+ if (Buffer.byteLength(out + char, 'utf8') > budget) break
36
+ out += char
37
+ }
38
+ return `${out}…`
39
+ }
40
+
41
+ /**
42
+ * Compose the session title prefix for one chat.
43
+ * @param input - platform, chatType, chatTitle, threadId, userName, userUsername, maxBytes.
44
+ * @returns a single-line label such as `TG · @vi468` or `TG · Argo Navis › topic 5122`.
45
+ */
46
+ export function chatLabel(input = {}) {
47
+ const {
48
+ platform, chatType, chatTitle, threadId, userName, userUsername, maxBytes = 60,
49
+ } = input
50
+ const tag = platformTag(platform)
51
+ const isPrivate = !chatType || chatType === 'private'
52
+ let base
53
+ if (isPrivate) {
54
+ const name = String(userName || chatTitle || '').trim() || 'DM'
55
+ const handle = String(userUsername || '').replace(/^@/, '').trim()
56
+ base = handle ? `@${handle}` : name
57
+ } else {
58
+ const title = String(chatTitle || '').trim() || 'group'
59
+ base = threadId ? `${title} › topic ${threadId}` : title
60
+ }
61
+ return truncateBytes(`${tag} · ${base.replace(/\s+/g, ' ')}`, maxBytes)
62
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-messenger-gateway",
3
- "version": "0.4.29",
3
+ "version": "0.4.30",
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",