@goodandready/dsh-messenger-gateway 0.4.29 → 0.4.31
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 +8 -1
- package/lib/adapters/index.js +1 -0
- package/lib/adapters/telegram.js +23 -3
- package/lib/commands.js +4 -0
- package/lib/config.js +6 -0
- package/lib/gateway-commands.js +132 -5
- package/lib/gateway.js +26 -0
- package/lib/index.js +12 -3
- package/lib/labels.js +62 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -48,9 +48,11 @@ 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
|
|
55
|
+
- Named sessions from chat metadata (`agent.sessionTitleFromChat`: `TG · @username` or `TG · Group › topic N`)
|
|
54
56
|
- Quick actions reply keyboard (`/keyboard on|off`)
|
|
55
57
|
- Multi-select interactive ask forms with checkboxes and pagination (`messenger_ask`)
|
|
56
58
|
- Artifact & Mermaid diagram rendering (SVG cards) and monospace table formatting
|
|
@@ -104,6 +106,8 @@ Spoken replies use Telegram `sendVoice`. If TTS returns MP3 (or other non-Opus a
|
|
|
104
106
|
| `/start` `/help` | Help |
|
|
105
107
|
| `/whoami` | Your Telegram user id |
|
|
106
108
|
| `/new` | New agent session |
|
|
109
|
+
| `/sessions` | List recent messenger conversations |
|
|
110
|
+
| `/resume <n|id>` | Switch chat to previous session |
|
|
107
111
|
| `/stop` | Abort the current turn |
|
|
108
112
|
| `/model` | Interactive 2-step model picker (providers → models) or `/model <prov> <mod>` |
|
|
109
113
|
| `/status` | Gateway status and session counters |
|
|
@@ -139,6 +143,9 @@ In addition to Telegram, outbound messages can be dispatched to Discord and Slac
|
|
|
139
143
|
## Configuration notes
|
|
140
144
|
|
|
141
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
|
|
148
|
+
- `sessionTitleFromChat`: `false` (default) — name each new session after its originating chat (`TG · @user`, `TG · Group › topic N`) instead of generic generated titles
|
|
142
149
|
- `voiceMode`: `mirror` / `always` / `off` — when to speak replies (also `/voice`)
|
|
143
150
|
- `tts.enabled` / `tts.maxChars` — TTS gate and length cap
|
|
144
151
|
- `notifyBridge` — forward non-messenger web session events to a home
|
package/lib/adapters/index.js
CHANGED
|
@@ -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,
|
package/lib/adapters/telegram.js
CHANGED
|
@@ -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 || {}
|
|
@@ -93,14 +94,21 @@ export class TelegramAdapter {
|
|
|
93
94
|
this.allowedUserIds = (ids || []).map(Number).filter((n) => Number.isFinite(n))
|
|
94
95
|
}
|
|
95
96
|
|
|
96
|
-
async call(method, params = {}) {
|
|
97
|
+
async call(method, params = {}, externalSignal) {
|
|
97
98
|
const timeoutMs = (this.timeoutSeconds * 1000) + 15000
|
|
99
|
+
// A long poll holds its request open for `timeoutSeconds`, so stopping the
|
|
100
|
+
// adapter has to cancel it: otherwise a reloaded instance keeps processing
|
|
101
|
+
// updates with the code that is already gone.
|
|
102
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs)
|
|
103
|
+
const signal = externalSignal && typeof AbortSignal.any === 'function'
|
|
104
|
+
? AbortSignal.any([timeoutSignal, externalSignal])
|
|
105
|
+
: externalSignal || timeoutSignal
|
|
98
106
|
const fetchOpts = {
|
|
99
107
|
method: 'POST',
|
|
100
108
|
headers: { 'Content-Type': 'application/json' },
|
|
101
109
|
body: JSON.stringify(params),
|
|
102
110
|
keepalive: true,
|
|
103
|
-
signal
|
|
111
|
+
signal,
|
|
104
112
|
}
|
|
105
113
|
const res = await this.apiFetch(`${this.apiRoot}/bot${this.token}/${method}`, fetchOpts)
|
|
106
114
|
const json = await res.json().catch(() => ({}))
|
|
@@ -252,6 +260,7 @@ export class TelegramAdapter {
|
|
|
252
260
|
|
|
253
261
|
stop() {
|
|
254
262
|
this.stopped = true
|
|
263
|
+
try { this.pollAbort?.abort() } catch { /* best effort */ }
|
|
255
264
|
if (this.mediaGroups) {
|
|
256
265
|
for (const group of this.mediaGroups.values()) {
|
|
257
266
|
if (group.timeout) clearTimeout(group.timeout)
|
|
@@ -273,13 +282,15 @@ export class TelegramAdapter {
|
|
|
273
282
|
|
|
274
283
|
async poll() {
|
|
275
284
|
if (this.stopped) return
|
|
285
|
+
this.pollAbort = new AbortController()
|
|
286
|
+
const signal = this.pollAbort.signal
|
|
276
287
|
let backoffDelay
|
|
277
288
|
try {
|
|
278
289
|
const updates = await this.call('getUpdates', {
|
|
279
290
|
timeout: this.timeoutSeconds,
|
|
280
291
|
offset: this.offset,
|
|
281
292
|
allowed_updates: ['message', 'callback_query'],
|
|
282
|
-
})
|
|
293
|
+
}, signal)
|
|
283
294
|
this.pollingConflict = false
|
|
284
295
|
this.pollErrorCount = 0
|
|
285
296
|
for (const update of updates || []) {
|
|
@@ -372,6 +383,9 @@ export class TelegramAdapter {
|
|
|
372
383
|
|
|
373
384
|
allowed(userId) {
|
|
374
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
|
+
}
|
|
375
389
|
return this.allowedUserIds.length === 0 || this.allowedUserIds.includes(Number(userId))
|
|
376
390
|
}
|
|
377
391
|
|
|
@@ -515,6 +529,9 @@ export class TelegramAdapter {
|
|
|
515
529
|
|
|
516
530
|
await this.onMessage({
|
|
517
531
|
platform: 'telegram', chatId, userId, threadId, chatType, text,
|
|
532
|
+
chatTitle: primaryMsg.chat?.title,
|
|
533
|
+
userName: [primaryMsg.from?.first_name, primaryMsg.from?.last_name].filter(Boolean).join(' '),
|
|
534
|
+
userUsername: primaryMsg.from?.username,
|
|
518
535
|
attachments: allAttachments, replyText,
|
|
519
536
|
messageId, reply, typing, startStream, startProgress, react,
|
|
520
537
|
})
|
|
@@ -583,6 +600,9 @@ export class TelegramAdapter {
|
|
|
583
600
|
|
|
584
601
|
await this.onMessage({
|
|
585
602
|
platform: 'telegram', chatId, userId, threadId, chatType, text, attachments, replyText,
|
|
603
|
+
chatTitle: msg.chat?.title,
|
|
604
|
+
userName: [msg.from?.first_name, msg.from?.last_name].filter(Boolean).join(' '),
|
|
605
|
+
userUsername: msg.from?.username,
|
|
586
606
|
messageId, reply, typing, startStream, startProgress, react,
|
|
587
607
|
})
|
|
588
608
|
}
|
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({
|
|
@@ -127,6 +129,10 @@ export const PluginConfig = z.object({
|
|
|
127
129
|
photoOnlyMode: z.union([z.const('prompt'), z.const('run')]).default('prompt'),
|
|
128
130
|
sessionScope: z.union([z.const('chat'), z.const('user')]).default('user')
|
|
129
131
|
.description('In groups: user = per-user session; chat = shared session for the chat/topic'),
|
|
132
|
+
sessionTitleFromChat: z.boolean().default(false)
|
|
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'),
|
|
130
136
|
}).volatile(),
|
|
131
137
|
})
|
|
132
138
|
|
package/lib/gateway-commands.js
CHANGED
|
@@ -496,17 +496,144 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
496
496
|
}
|
|
497
497
|
|
|
498
498
|
|
|
499
|
-
|
|
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 <number></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
|
+
}
|
|
500
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
|
+
|
|
501
579
|
if (chat) {
|
|
502
580
|
if (chat.abort) chat.abort.abort()
|
|
503
581
|
chat.pendingMedia = []
|
|
504
|
-
gw.sessionToChat.delete(String(chat.agent.session.id))
|
|
505
582
|
gw.chats.delete(key)
|
|
506
|
-
|
|
507
|
-
|
|
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}`)
|
|
508
605
|
}
|
|
509
|
-
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
if (cmd === '/new') {
|
|
609
|
+
const chat = gw.chats.get(key)
|
|
610
|
+
if (!chat) return reply(t('msg.no_active_session', {}, locale))
|
|
611
|
+
if (chat.abort) chat.abort.abort()
|
|
612
|
+
chat.pendingMedia = []
|
|
613
|
+
const sessionId = String(chat.agent?.session?.id || '')
|
|
614
|
+
// Detach every mapping before disposing. A surviving `threadToSession` (or
|
|
615
|
+
// `sessionToThread`) entry makes the next inbound message resume the very
|
|
616
|
+
// session that is being torn down, which DSH rejects with
|
|
617
|
+
// "cannot append outside a SessionStore" / "cannot create effect on an
|
|
618
|
+
// inactive context".
|
|
619
|
+
gw.chats.delete(key)
|
|
620
|
+
if (sessionId) {
|
|
621
|
+
gw.sessionToChat.delete(sessionId)
|
|
622
|
+
gw.sessionToThread.delete(sessionId)
|
|
623
|
+
}
|
|
624
|
+
const target = chat.target || {}
|
|
625
|
+
gw.threadToSession.delete(`${target.chatId ?? input.chatId}:${target.threadId ?? input.threadId ?? 0}`)
|
|
626
|
+
// Dispose out of band: abort() just fired, and awaiting the teardown in the
|
|
627
|
+
// same tick lets the draining turn append a closing event after the store
|
|
628
|
+
// closed. The command reply must not wait for that drain either.
|
|
629
|
+
setImmediate(() => {
|
|
630
|
+
try {
|
|
631
|
+
chat.dispose?.().catch?.((err) => gw.logger?.warn?.(`/new dispose: ${err?.message || err}`))
|
|
632
|
+
} catch (err) {
|
|
633
|
+
gw.logger?.warn?.(`/new dispose: ${err?.message || err}`)
|
|
634
|
+
}
|
|
635
|
+
})
|
|
636
|
+
return reply('Session reset.')
|
|
510
637
|
}
|
|
511
638
|
|
|
512
639
|
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'
|
|
@@ -200,6 +201,10 @@ export class Gateway {
|
|
|
200
201
|
|
|
201
202
|
isUserAllowed(userId) {
|
|
202
203
|
const ids = this.effectiveAllowedIds()
|
|
204
|
+
const mode = this.tg()?.allowlistMode || 'open'
|
|
205
|
+
if (mode === 'closed') {
|
|
206
|
+
return ids.length > 0 && ids.includes(Number(userId))
|
|
207
|
+
}
|
|
203
208
|
return ids.length === 0 || ids.includes(Number(userId))
|
|
204
209
|
}
|
|
205
210
|
|
|
@@ -299,6 +304,9 @@ export class Gateway {
|
|
|
299
304
|
this.adapterList = this.adapterList.filter((item) => item !== adapter)
|
|
300
305
|
if (this.tgAdapter === adapter) this.tgAdapter = undefined
|
|
301
306
|
}
|
|
307
|
+
if ((this.tg()?.allowlistMode || 'open') === 'open' && this.effectiveAllowedIds().length === 0) {
|
|
308
|
+
this.ctx.logger?.warn?.('[dsh-messenger-gateway] telegram allowlist is empty in "open" mode: the bot will accept messages from any Telegram user.')
|
|
309
|
+
}
|
|
302
310
|
for (const adapter of adapters) {
|
|
303
311
|
// Регистрируем адаптер ДО `await adapter.start()`: старт адаптера — это
|
|
304
312
|
// сетевые вызовы (getMe/setMyCommands/deleteWebhook), и если за это время
|
|
@@ -664,6 +672,24 @@ export class Gateway {
|
|
|
664
672
|
})
|
|
665
673
|
await handle.agent.whenIdle()
|
|
666
674
|
await registerSessionInWorkspace(this.ctx, targetSessionId, cwd, this.ctx.logger).catch(() => {})
|
|
675
|
+
// Opt-in: name the session after the chat that opened it, so a bot serving
|
|
676
|
+
// several chats keeps an unambiguous session list.
|
|
677
|
+
if (!existingSessionId && agentCfg.sessionTitleFromChat === true) {
|
|
678
|
+
try {
|
|
679
|
+
const titleService = this.ctx.get?.('sessionTitle') ?? this.ctx.sessionTitle
|
|
680
|
+
const label = chatLabel({
|
|
681
|
+
platform: input?.platform,
|
|
682
|
+
chatType: input?.chatType,
|
|
683
|
+
chatTitle: input?.chatTitle,
|
|
684
|
+
threadId: input?.threadId || 0,
|
|
685
|
+
userName: input?.userName,
|
|
686
|
+
userUsername: input?.userUsername,
|
|
687
|
+
})
|
|
688
|
+
if (titleService?.rename && label) titleService.rename(handle.agent.session, label)
|
|
689
|
+
} catch (err) {
|
|
690
|
+
this.ctx.logger?.warn?.(`[dsh-messenger-gateway] session title rename failed: ${err?.message || err}`)
|
|
691
|
+
}
|
|
692
|
+
}
|
|
667
693
|
const chat = {
|
|
668
694
|
key, agent: handle.agent, dispose: handle.dispose, busy: Promise.resolve(),
|
|
669
695
|
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
|
-
|
|
703
|
-
|
|
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.
|
|
3
|
+
"version": "0.4.31",
|
|
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",
|