@goodandready/dsh-messenger-gateway 0.3.19 → 0.3.21

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/lib/gateway.js CHANGED
@@ -1,1406 +1,1737 @@
1
- import { readFile } from 'node:fs/promises'
2
- import { randomUUID } from 'node:crypto'
3
- import { join } from 'node:path'
4
- import { homedir } from 'node:os'
5
- import { installModelSelection } from '@deepseek-ai/dsh-agent'
6
- import { createUserMessage } from '@deepseek-ai/dsh-llm'
7
- import { SessionId } from '@deepseek-ai/dsh-session'
8
- import createAdapters from './adapters/index.js'
9
- import { transcribeVoice, speakText } from './integrations.js'
10
- import { attachInboundPhoto, photoOnlyHint } from './photos.js'
11
- import { formatInboundDocument, documentOnlyHint, parseDocument } from './documents.js'
12
- import { listFiles, getFileForDownload, formatFileSize } from './file-manager.js'
13
- import { collectAssistantParts, buildOutboundFiles, stripImageUrls } from './outbound.js'
14
- import { assistantText, splitText, stripReasoningPreamble, MESSENGER_RELAY_INSTRUCTION } from './text.js'
15
- import { chatKey, sessionKey } from './topics.js'
16
- import { listHomes, resolveNamedHome, upsertHome, normalizeHomeName } from './homes.js'
17
- import { createVoicePrefs, shouldSpeakReply } from './voice-prefs.js'
18
- import { prepareTtsText, toTelegramVoiceFile } from './tts.js'
19
- import {
20
- makeAskToken, buildInlineKeyboard, buildMultiSelectKeyboard, indexCallbacks, releaseCallbacks,
21
- parseCallbackData, parseAskCallback, targetMatchesAsk, rejectPendingAsk, REMOVE_KEYBOARD,
22
- } from './ask.js'
23
- import { processDiagramsAndTables } from './artifacts.js'
24
- import { createPersonaStore, getPersona, listPersonas, BUILTIN_PERSONAS } from './personas.js'
25
- import { exportSessionToMarkdown, rewindSession } from './session-ops.js'
26
- import { formatAlertMessage, resolveAlertTarget } from './alerts.js'
27
- import { createScheduler, parseRelativeTime, formatRemaining } from './scheduler.js'
28
- import { listModelCatalog, buildProvidersKeyboard, buildModelsKeyboard, getStoredModelSelection } from './models.js'
29
- import { buildQuickActionsKeyboard, REMOVE_REPLY_KEYBOARD } from './adapters/telegram.js'
30
- import { createPairingStore } from './pairing.js'
31
- import {
32
- extractTextDelta, extractToolName, buildStreamPreview, formatProgressLine,
33
- createEditScheduler, startTypingHeartbeat,
34
- } from './stream.js'
35
- import { isTopicGoneError } from './telegram-errors.js'
36
- import { ensureContentArray } from './content-guard.js'
37
-
38
-
39
- function whenIdleWithTimeout(agent, timeoutMs, signal) {
40
- const idle = agent.whenIdle()
41
- if (!timeoutMs || timeoutMs <= 0) return idle
42
- return Promise.race([
43
- idle,
44
- new Promise((_, reject) => {
45
- const timer = setTimeout(() => reject(new Error(`turn timeout (${timeoutMs}ms)`)), timeoutMs)
46
- timer.unref?.()
47
- signal?.addEventListener('abort', () => { clearTimeout(timer); reject(new DOMException('Aborted', 'AbortError')) }, { once: true })
48
- }),
49
- ])
50
- }
51
-
52
- function releaseChatTurn(chat) {
53
- chat.busy = Promise.resolve()
54
- }
55
-
56
- const PLUGIN = 'dsh-messenger-gateway'
57
-
58
- export class Gateway {
59
- constructor(ctx, config, hooks = {}) {
60
- this.ctx = ctx
61
- this.config = config
62
- this.hooks = hooks
63
- this.chats = new Map()
64
- this.sessionToChat = new Map()
65
- this.pending = new Map()
66
- this.pendingAsks = new Map()
67
- this.adapters = new Map()
68
- this.adapterList = []
69
- this.disposeListener = undefined
70
- this.idleTimer = undefined
71
- this.callbackIndex = new Map()
72
- const home = process.env.DSH_HOME || join(homedir(), '.dsh')
73
- this.pairing = createPairingStore(join(home, 'messenger-gateway', 'pairing.json'))
74
- this.voicePrefs = createVoicePrefs(join(home, 'messenger-gateway', 'voice-prefs.json'))
75
- this.chatTts = createVoicePrefs(join(home, 'messenger-gateway', 'chat-tts.json'))
76
- this.muted = createVoicePrefs(join(home, 'messenger-gateway', 'muted.json'))
77
- this.personas = createPersonaStore(join(home, 'messenger-gateway', 'personas.json'))
78
- this.scheduler = createScheduler(join(home, 'messenger-gateway', 'scheduled.json'), async (task) => {
79
- const target = {
80
- platform: task.platform || 'telegram',
81
- chatId: task.chatId,
82
- threadId: task.threadId || 0,
83
- }
84
- const text = `⏰ <b>[Напоминание]</b>\n${task.text}`
85
- await this.sendToMessenger(target, { text })
86
- })
87
- this.stats = { sent: 0, errors: 0, startedAt: Date.now() }
88
- }
89
-
90
- isMuted(chatId) { return this.muted.get(chatId) === true }
91
- setMuted(chatId, on) { return this.muted.set(chatId, on) }
92
-
93
- baseUrl() {
94
- const raw = String(this.config.internalBaseURL || '').trim()
95
- return raw || 'http://127.0.0.1:3080'
96
- }
97
-
98
- tg() { return this.config.telegram || {} }
99
-
100
- effectiveAllowedIds() {
101
- const fromConfig = (this.tg().allowedUserIds || []).map(Number).filter(Number.isFinite)
102
- const fromPairing = this.pairing.listApproved()
103
- return [...new Set([...fromConfig, ...fromPairing])]
104
- }
105
-
106
- isUserAllowed(userId) {
107
- const ids = this.effectiveAllowedIds()
108
- return ids.length === 0 || ids.includes(Number(userId))
109
- }
110
-
111
- resolveHomeTarget(platform = 'telegram', name) {
112
- const tg = this.tg()
113
- const home = resolveNamedHome(tg, name)
114
- if (!home) return null
115
- const out = { platform, chatId: home.chatId, homeName: home.name }
116
- if (home.threadId > 0) out.threadId = home.threadId
117
- return out
118
- }
119
-
120
- async sendAlert(type, payload = {}) {
121
- try {
122
- const target = resolveAlertTarget(this)
123
- if (!target) return
124
- const allowedEvents = this.config.telegram?.alerts?.events || ['error', 'pairing']
125
- if (type !== 'status' && !allowedEvents.includes(type)) return
126
-
127
- const text = formatAlertMessage(type, payload)
128
- await this.sendToMessenger(target, { text })
129
- } catch (err) {
130
- this.ctx.logger?.warn?.(`sendAlert (${type}): ${err.message}`)
131
- }
132
- }
133
-
134
- async start() {
135
- this.disposeListener = this.ctx.on('session/event', (session, event) => {
136
- const collector = this.pending.get(session.id)
137
- if (!collector) return
138
- if (event.type === 'assistant/message') {
139
- const msg = event.data.message
140
- const text = assistantText(msg)
141
- if (text) collector.lastText = text
142
- const extra = collectAssistantParts(msg)
143
- for (const img of extra.images) collector.images.push(img)
144
- } else if (event.type === 'assistant/chunk') {
145
- const delta = extractTextDelta(event.data?.chunk)
146
- if (delta) {
147
- collector.streamText = (collector.streamText || '') + delta
148
- collector.onStream?.(collector.streamText, collector.toolName)
149
- }
150
- } else if (event.type === 'tool/call') {
151
- collector.toolName = extractToolName(event.data) || collector.toolName
152
- collector.onStream?.(collector.streamText || '', collector.toolName)
153
- } else if (event.type === 'tool/result') {
154
- collector.toolName = ''
155
- collector.onStream?.(collector.streamText || '', '')
156
- } else if (event.type === 'turn/end') {
157
- collector.reason = event.data.reason
158
- }
159
- })
160
- const adapters = createAdapters({
161
- config: this.config,
162
- onMessage: (input) => this.handleMessage(input),
163
- onCallback: (cb) => this.handleCallback(cb),
164
- onUnauthorized: (input) => this.handleUnauthorized(input),
165
- isUserAllowed: (id) => this.isUserAllowed(id),
166
- logger: this.ctx.logger,
167
- })
168
- for (const adapter of adapters) {
169
- try {
170
- await adapter.start()
171
- this.adapterList.push(adapter)
172
- this.adapters.set(adapter.name, adapter)
173
- if (adapter.name === 'telegram') this.tgAdapter = adapter
174
- this.ctx.logger?.info?.(`dsh-messenger-gateway: ${adapter.name} started`)
175
- } catch (err) {
176
- this.ctx.logger?.warn?.(`dsh-messenger-gateway: ${adapter.name}: ${err.message}`)
177
- }
178
- }
179
- const rawIdle = Number(this.config.agent?.idleTimeoutMs)
180
- const idleMs = Number.isFinite(rawIdle) && rawIdle > 0 ? rawIdle : 86_400_000
181
- this.idleTimer = setInterval(() => this.reapIdle(), Math.min(idleMs, 60_000))
182
- this.idleTimer.unref?.()
183
- this.scheduler.start()
184
- }
185
-
186
- stop() {
187
- if (this.scheduler) this.scheduler.stop()
188
- if (this.disposeListener) this.disposeListener()
189
- if (this.idleTimer) clearInterval(this.idleTimer)
190
- for (const a of this.adapterList) { try { a.stop() } catch {} }
191
- this.adapterList = []
192
- this.adapters.clear()
193
- for (const chat of this.chats.values()) chat.dispose().catch(() => {})
194
- this.chats.clear()
195
- this.sessionToChat.clear()
196
- for (const pending of this.pendingAsks.values()) {
197
- releaseCallbacks(this.callbackIndex, pending.callbackKeys)
198
- rejectPendingAsk(pending, new Error('gateway stopped'))
199
- }
200
- this.pending.clear()
201
- this.pendingAsks.clear()
202
- this.callbackIndex.clear()
203
- }
204
-
205
- getAdapter(platform) { return this.adapters.get(platform) }
206
-
207
- async messengerSend(target, payload) {
208
- let resolved = target
209
- if (!resolved?.chatId && resolved?.platform) {
210
- const home = this.resolveHomeTarget(resolved.platform, resolved.home || resolved.name)
211
- if (!home) throw new Error('target.chatId required (or set telegram home channel)')
212
- resolved = { ...home, ...resolved, chatId: home.chatId, threadId: resolved.threadId ?? home.threadId }
213
- }
214
- const adapter = this.getAdapter(resolved.platform)
215
- if (!adapter?.sendTo) throw new Error(`adapter ${resolved.platform} unavailable`)
216
- try {
217
- await adapter.sendTo(resolved.chatId, payload, { threadId: resolved.threadId })
218
- this.stats.sent++
219
- } catch (err) {
220
- this.stats.errors++
221
- if (isTopicGoneError(err)) {
222
- this.logger?.warn?.(`messengerSend: topic gone for ${resolved.platform}:${resolved.chatId}:${resolved.threadId} — the chat/topic was deleted; skipping delivery`)
223
- return
224
- }
225
- throw err
226
- }
227
- }
228
-
229
- async messengerAsk(target, payload, timeoutMs = 300_000) {
230
- const adapter = this.getAdapter(target.platform)
231
- if (!adapter) throw new Error(`adapter ${target.platform} unavailable`)
232
- const token = makeAskToken()
233
- const isMulti = payload.mode === 'multi' || (Array.isArray(payload.options) && payload.options.length > 0)
234
- let replyMarkup
235
- let callbackKeys
236
- let selectedSet
237
- let page = 0
238
- const pageSize = Number(payload.pageSize) || 6
239
-
240
- if (isMulti) {
241
- selectedSet = new Set(Array.isArray(payload.selected) ? payload.selected : [])
242
- const kb = buildMultiSelectKeyboard(token, payload.options || payload.buttons, selectedSet, page, pageSize, payload)
243
- replyMarkup = kb.replyMarkup
244
- callbackKeys = kb.callbackKeys
245
- } else {
246
- const kb = buildInlineKeyboard(token, payload.buttons || [])
247
- replyMarkup = kb.replyMarkup
248
- callbackKeys = kb.callbackKeys
249
- }
250
-
251
- indexCallbacks(this.callbackIndex, callbackKeys, token)
252
- try {
253
- await adapter.sendTo(target.chatId, { text: payload.text, replyMarkup }, { threadId: target.threadId })
254
- } catch (err) {
255
- // Never leave stale callback keys pointing at an unresolvable ask.
256
- releaseCallbacks(this.callbackIndex, callbackKeys)
257
- if (isTopicGoneError(err)) {
258
- this.logger?.warn?.(`messengerAsk: topic gone for ${target.platform}:${target.chatId}:${target.threadId} — ask aborted (chat/topic deleted)`)
259
- throw new Error('messenger.ask: chat or topic was deleted')
260
- }
261
- throw err
262
- }
263
- return new Promise((resolve, reject) => {
264
- const timer = setTimeout(() => {
265
- this.pendingAsks.delete(token)
266
- releaseCallbacks(this.callbackIndex, callbackKeys)
267
- reject(new Error('messenger.ask timed out'))
268
- }, timeoutMs)
269
- timer.unref?.()
270
- this.pendingAsks.set(token, {
271
- resolve, reject, timer, target, callbackKeys, isMulti,
272
- options: payload.options || payload.buttons,
273
- selected: selectedSet,
274
- page, pageSize, payload,
275
- })
276
- })
277
- }
278
-
279
- async messengerProgress(target, payload) {
280
- await this.messengerSend(target, { text: payload.text })
281
- }
282
-
283
- async handleUnauthorized(input) {
284
- const { reply, userId, username } = input
285
- if (!this.tg().pairingEnabled) {
286
- await reply('Доступ закрыт. Попросите владельца добавить ваш id в allowlist.')
287
- return
288
- }
289
- try {
290
- const { code } = this.pairing.requestCode(userId, { username })
291
- await reply(`Нет доступа.\nВаш id: ${userId}\nКод сопряжения: ${code}\n\nВладелец должен отправить боту:\n/pair ${code}`)
292
- this.sendAlert('pairing', { userId, username, code }).catch(() => {})
293
- } catch (err) {
294
- if (err.code === 'RATE_LIMIT') await reply('Код уже выдан. Подождите или попросите владельца /pair.')
295
- else await reply(`Не удалось выдать код: ${err.message}`)
296
- }
297
- }
298
-
299
- async handleCallback(cb) {
300
- if (cb.userId && !this.isUserAllowed(cb.userId)) {
301
- try { await cb.answer('Нет доступа.') } catch {}
302
- return
303
- }
304
- const indexed = this.callbackIndex.get(cb.data)
305
- const { token, buttonId } = parseCallbackData(cb.data)
306
- const askToken = indexed || token
307
- if (askToken && this.pendingAsks.has(askToken)) {
308
- const pending = this.pendingAsks.get(askToken)
309
- if (!targetMatchesAsk(pending, cb)) {
310
- await cb.answer('Кнопка для другого чата')
311
- return
312
- }
313
- const action = parseAskCallback(cb.data)
314
- if (pending.isMulti) {
315
- if (action.kind === 'toggle') {
316
- if (pending.selected.has(action.id)) pending.selected.delete(action.id)
317
- else pending.selected.add(action.id)
318
- releaseCallbacks(this.callbackIndex, pending.callbackKeys)
319
- const nextKb = buildMultiSelectKeyboard(askToken, pending.options, pending.selected, pending.page, pending.pageSize, pending.payload)
320
- pending.callbackKeys = nextKb.callbackKeys
321
- indexCallbacks(this.callbackIndex, nextKb.callbackKeys, askToken)
322
- try {
323
- if (cb.editReplyMarkup) await cb.editReplyMarkup(nextKb.replyMarkup)
324
- else await cb.editMessage(cb.message?.text || 'Выбор', nextKb.replyMarkup)
325
- } catch {}
326
- await cb.answer(pending.selected.has(action.id) ? 'Выбрано' : 'Снято')
327
- return
328
- }
329
- if (action.kind === 'page') {
330
- pending.page = action.page
331
- releaseCallbacks(this.callbackIndex, pending.callbackKeys)
332
- const nextKb = buildMultiSelectKeyboard(askToken, pending.options, pending.selected, pending.page, pending.pageSize, pending.payload)
333
- pending.callbackKeys = nextKb.callbackKeys
334
- indexCallbacks(this.callbackIndex, nextKb.callbackKeys, askToken)
335
- try {
336
- if (cb.editReplyMarkup) await cb.editReplyMarkup(nextKb.replyMarkup)
337
- else await cb.editMessage(cb.message?.text || 'Выбор', nextKb.replyMarkup)
338
- } catch {}
339
- await cb.answer()
340
- return
341
- }
342
- if (action.kind === 'done') {
343
- this.pendingAsks.delete(askToken)
344
- clearTimeout(pending.timer)
345
- releaseCallbacks(this.callbackIndex, pending.callbackKeys)
346
- await cb.answer('OK')
347
- try { await cb.editMessage(cb.message?.text || 'Выбрано', REMOVE_KEYBOARD) } catch {}
348
- pending.resolve({ buttonId: 'done', selected: Array.from(pending.selected), data: cb.data })
349
- return
350
- }
351
- if (action.kind === 'cancel') {
352
- this.pendingAsks.delete(askToken)
353
- clearTimeout(pending.timer)
354
- releaseCallbacks(this.callbackIndex, pending.callbackKeys)
355
- await cb.answer('Отменено')
356
- try { await cb.editMessage(cb.message?.text || 'Отменено', REMOVE_KEYBOARD) } catch {}
357
- pending.resolve({ buttonId: 'cancel', selected: [], data: cb.data })
358
- return
359
- }
360
- }
361
- this.pendingAsks.delete(askToken)
362
- clearTimeout(pending.timer)
363
- releaseCallbacks(this.callbackIndex, pending.callbackKeys)
364
- await cb.answer('OK')
365
- try { await cb.editMessage(cb.message?.text || 'Выбрано', REMOVE_KEYBOARD) } catch {}
366
- pending.resolve({ buttonId: action.id || buttonId, data: cb.data })
367
- return
368
- }
369
-
370
- // Model picker interactive flow
371
- if (cb.data?.startsWith('mdl:')) {
372
- const parts = cb.data.split(':')
373
- const sub = parts[1]
374
- // Step 2: Selected provider -> show its models (10 per page)
375
- if (sub === 'p') {
376
- const providerId = parts.slice(2).join(':')
377
- const current = this.resolveAgentModel()
378
- const catalog = await listModelCatalog(this.ctx, current)
379
- const models = catalog.modelsByProvider.get(providerId) || []
380
- if (!models.length) {
381
- await cb.answer('Нет доступных моделей у этого провайдера')
382
- return
383
- }
384
- const kb = buildModelsKeyboard(providerId, models, current.model, 0)
385
- await cb.answer()
386
- const text = [
387
- `🤖 <b>Провайдер:</b> <code>${providerId}</code>`,
388
- `Выберите модель (страница ${kb.page + 1}/${kb.totalPages}):`,
389
- ].join('\n')
390
- try {
391
- if (cb.editMessage) await cb.editMessage(text, kb)
392
- } catch {}
393
- return
394
- }
395
- // Pagination for models
396
- if (sub === 'pg') {
397
- const page = parseInt(parts[parts.length - 1], 10) || 0
398
- const providerId = parts.slice(2, -1).join(':')
399
- const current = this.resolveAgentModel()
400
- const catalog = await listModelCatalog(this.ctx, current)
401
- const models = catalog.modelsByProvider.get(providerId) || []
402
- const kb = buildModelsKeyboard(providerId, models, current.model, page)
403
- await cb.answer()
404
- const text = [
405
- `🤖 <b>Провайдер:</b> <code>${providerId}</code>`,
406
- `Выберите модель (страница ${kb.page + 1}/${kb.totalPages}):`,
407
- ].join('\n')
408
- try {
409
- if (cb.editMessage) await cb.editMessage(text, kb)
410
- } catch {}
411
- return
412
- }
413
- // Back to providers
414
- if (sub === 'back') {
415
- const current = this.resolveAgentModel()
416
- const catalog = await listModelCatalog(this.ctx, current)
417
- const kb = buildProvidersKeyboard(catalog.providers, current)
418
- await cb.answer()
419
- const text = [
420
- '🤖 <b>Выберите провайдера:</b>',
421
- `Текущая: <code>${current.provider}/${current.model}</code>`,
422
- ].join('\n')
423
- try {
424
- if (cb.editMessage) await cb.editMessage(text, kb)
425
- } catch {}
426
- return
427
- }
428
- // Select model
429
- if (sub === 's') {
430
- const key = parts[2]
431
- const stored = getStoredModelSelection(key)
432
- if (!stored) {
433
- await cb.answer('Сессия выбора модели истекла, вызовите /model заново')
434
- return
435
- }
436
- const { provider, model } = stored
437
- try {
438
- const adm = this.ctx.get('agentDefaultModel')
439
- if (adm?.saveSelection) {
440
- await adm.saveSelection({ provider, model })
441
- }
442
- this.config.agent = { ...this.config.agent, provider, model }
443
- try {
444
- await this.hooks?.persistAgentModel?.({ provider, model })
445
- } catch (e) {
446
- this.ctx.logger?.warn?.(`persist agent model: ${e.message}`)
447
- }
448
- await cb.answer(`Выбрана ${model}`)
449
- try {
450
- if (cb.editMessage) await cb.editMessage(`✅ Модель успешно переключена на: <b>${provider}/${model}</b>`, REMOVE_KEYBOARD)
451
- } catch {}
452
- } catch (err) {
453
- await cb.answer(`Ошибка: ${err.message}`)
454
- }
455
- return
456
- }
457
- if (sub === 'cur') {
458
- await cb.answer()
459
- return
460
- }
461
- }
462
-
463
- await cb.answer()
464
- }
465
-
466
- sessionKeyFor(input) {
467
- const scope = this.config.agent?.sessionScope || 'user'
468
- return sessionKey({
469
- platform: input.platform,
470
- chatId: input.chatId,
471
- threadId: input.threadId || 0,
472
- userId: input.userId,
473
- chatType: input.chatType,
474
- scope,
475
- })
476
- }
477
-
478
- isChatBusy(chat) {
479
- return Boolean(chat?.turnActive)
480
- }
481
-
482
- async handleMessage(input) {
483
- const { platform, chatId, threadId = 0, text, reply } = input
484
- const key = this.sessionKeyFor(input)
485
- const body = String(text || '').trim()
486
- let attachments = [...(input.attachments || [])]
487
- const hasMedia = attachments.length > 0
488
- if (!body && !hasMedia) return
489
- if (body.startsWith('/')) { await this.handleCommand(key, body, input); return }
490
- try {
491
- const chat = await this.getOrCreateChat(key, input)
492
- const photoOnlyMode = this.config.agent?.photoOnlyMode ?? 'prompt'
493
- const incomingPhotoOnly = hasMedia && attachments.every((a) => a.kind === 'photo' || a.kind === 'sticker') && !body
494
- if (incomingPhotoOnly && photoOnlyMode === 'prompt') {
495
- chat.pendingMedia = [...(chat.pendingMedia || []), ...attachments]
496
- const n = chat.pendingMedia.length
497
- const msg = n === 1
498
- ? 'Медиа получено. Напишите вопрос — например: «что на фото?»'
499
- : `Получено ${n} вложений. Напишите вопрос.`
500
- return reply(msg)
501
- }
502
- if (chat.pendingMedia?.length) {
503
- attachments = [...chat.pendingMedia, ...attachments]
504
- chat.pendingMedia = []
505
- }
506
- const inboundWasVoice = attachments.some((a) => a.kind === 'voice' || a.kind === 'audio')
507
- let personaOverride
508
- for (const [pId] of Object.entries(BUILTIN_PERSONAS)) {
509
- if (pId === 'default') continue
510
- const tag = `@${pId}`
511
- if (body.toLowerCase().includes(tag)) {
512
- personaOverride = pId
513
- break
514
- }
515
- }
516
- const turnInput = { ...input, text: body, attachments, inboundWasVoice, personaOverride }
517
-
518
- // Hermes-like steer: while a turn is running, inject followup instead of abort+restart
519
- if (this.isChatBusy(chat)) {
520
- const steerText = body || (hasMedia ? '(дополнение: медиа)' : '')
521
- const content = await this.buildUserContent({
522
- ...turnInput,
523
- text: steerText,
524
- steer: true,
525
- }, undefined)
526
- chat.agent.followup(createUserMessage({
527
- content: ensureContentArray(content),
528
- source: { kind: 'plugin', plugin: PLUGIN, form: 'steer' },
529
- }))
530
- chat.lastUsed = Date.now()
531
- try { await reply('↪️ Добавлено к текущему ответу') } catch {}
532
- return
533
- }
534
-
535
- // Mark busy BEFORE yielding to the poll loop, otherwise steer/stop never see an active turn.
536
- chat.turnActive = true
537
- try { chat.abort?.abort?.() } catch {}
538
- chat.abort = new AbortController()
539
- const run = chat.busy.then(() => this.runTurn(chat, turnInput, chat.abort.signal))
540
- chat.busy = run.catch(() => {})
541
- // Do NOT await: Telegram poll is sequential; awaiting blocked steer and /stop until the turn finished.
542
- run.catch((err) => {
543
- const msg = err instanceof Error ? err.message : String(err)
544
- this.ctx.logger?.warn?.(`dsh-messenger-gateway: background turn: ${msg}`)
545
- this.sendAlert('error', {
546
- code: err?.code || 'BACKGROUND_ERROR',
547
- message: msg,
548
- sessionId: chat.agent?.session?.id,
549
- chatId: input.chatId,
550
- threadId: input.threadId,
551
- }).catch(() => {})
552
- chat.turnActive = false
553
- chat.abort = undefined
554
- })
555
- } catch (err) {
556
- const msg = err instanceof Error ? err.message : String(err)
557
- this.ctx.logger?.warn?.(`dsh-messenger-gateway: message: ${msg}`)
558
- try { await reply(`Ошибка: ${msg}`) } catch {}
559
- }
560
- }
561
-
562
- async handleCommand(key, text, input) {
563
-
564
- const parts = text.split(/\s+/)
565
- const cmd = parts[0].toLowerCase().split('@')[0]
566
- const { reply, userId, chatId, threadId = 0, platform } = input
567
- if (cmd === '/start') return reply('Шлюз подключён. Пишите сообщение агенту. /help — команды.', { replyMarkup: REMOVE_REPLY_KEYBOARD })
568
- if (cmd === '/help') {
569
- return reply([
570
- '📖 <b>Команды бота:</b>',
571
- '',
572
- '💬 <b>Диалог:</b>',
573
- '• /help эта справка',
574
- '• /new новая сессия',
575
- ' /stop — прервать текущий ответ',
576
- ' /model интерактивный выбор модели (/model list)',
577
- '• /role [name] — персоны и роли агента (/role list)',
578
- '• /rewind [N] — откат последних N ходов',
579
- '• /fork — форк сессии в новую ветку',
580
- '• /export выгрузка истории в Markdown',
581
- '',
582
- '🛠️ <b>Инструменты и файлы:</b>',
583
- '• /skills / /tools список активных инструментов',
584
- '• /files [dir] — проводник рабочей папки',
585
- '• /get <path> скачать файл в Telegram',
586
- '• /remind <время> <текст> — напоминание (/remind 10m текст)',
587
- '',
588
- '⚙️ <b>Настройки:</b>',
589
- '• /status — статус шлюза и модели',
590
- '• /top — системные ресурсы (RAM, uptime)',
591
- '• /keyboard on|off — быстрые кнопки',
592
- '• /voice on|off|status — голосовые ответы',
593
- '• /tts on|off|status озвучка в этом чате',
594
- '• /mute / /unmute — заглушить уведомления в этот чат',
595
- '',
596
- '🔒 <b>Доступ и каналы:</b>',
597
- '• /whoami ваш Telegram id',
598
- '• /pair CODE одобрить код сопряжения',
599
- '• /sethome [name] — привязать домашний чат',
600
- '• /setalert — назначить канал алертов',
601
- ].join('\n'))
602
- }
603
- if (cmd === '/role' || cmd === '/persona') {
604
- const targetRole = parts[1]?.toLowerCase()
605
- if (!targetRole || targetRole === 'list') {
606
- const currentId = this.personas.get(chatId)
607
- const lines = [
608
- '🎭 <b>Доступные роли и персоны:</b>',
609
- '',
610
- ...listPersonas().map((p) => {
611
- const isCurrent = p.id === currentId ? ' (активна)' : ''
612
- return `${p.icon} <b>${p.id}</b> ${p.name}: ${p.description}${isCurrent}`
613
- }),
614
- '',
615
- 'Смена роли: <code>/role coder</code> (или /role reset)',
616
- ]
617
- return reply(lines.join('\n'))
618
- }
619
- if (targetRole === 'reset' || targetRole === 'default') {
620
- this.personas.set(chatId, 'default')
621
- return reply('🎭 Роль сброшена на стандартную (Default).')
622
- }
623
- const persona = getPersona(targetRole)
624
- if (!persona) {
625
- return reply(`Неизвестная роль "${targetRole}". Список: /role list`)
626
- }
627
- this.personas.set(chatId, persona.id)
628
- return reply(`🎭 Роль изменена на: ${persona.icon} <b>${persona.name}</b>\n${persona.description}`)
629
- }
630
- if (cmd === '/skills' || cmd === '/tools') {
631
- const tools = this.ctx.get?.('tools') || this.ctx.tools
632
- if (tools?.tools) {
633
- for (const [name, t] of tools.tools.entries()) {
634
- toolsList.push(`• <b>${name}</b>: ${t.description || '(нет описания)'}`)
635
- }
636
- }
637
- if (!toolsList.length) {
638
- return reply('🛠️ <b>Инструменты агента:</b>\n(нет зарегистрированных инструментов)')
639
- }
640
- return reply([
641
- '🛠️ <b>Активные инструменты и скиллы:</b>',
642
- '',
643
- ...toolsList,
644
- ].join('\n'))
645
- }
646
- if (cmd === '/export') {
647
- const chat = this.chats.get(key)
648
- if (!chat?.agent?.session) {
649
- return reply('Нет активной сессии для экспорта.')
650
- }
651
- try {
652
- const { filename, buffer, messagesCount } = exportSessionToMarkdown(chat.agent.session)
653
- if (!messagesCount) {
654
- return reply('Сессия пуста, нет сообщений для экспорта.')
655
- }
656
- const file = {
657
- name: filename,
658
- mime: 'text/markdown',
659
- kind: 'document',
660
- bytes: buffer,
661
- }
662
- return reply({ text: `📄 Экспорт диалога (${messagesCount} сообщений):`, files: [file] })
663
- } catch (err) {
664
- return reply(`Ошибка экспорта: ${err.message}`)
665
- }
666
- }
667
- if (cmd === '/rewind') {
668
- const chat = this.chats.get(key)
669
- if (!chat?.agent?.session) {
670
- return reply('Нет активной сессии для отката.')
671
- }
672
- const count = Number(parts[1]) || 1
673
- const res = rewindSession(chat.agent.session, count)
674
- if (!res.removed) {
675
- return reply('В истории сессии нет сообщений для отката.')
676
- }
677
- const sessions = this.ctx.get?.('sessions') || this.ctx.sessions
678
- try { await sessions?.flush(chat.agent.session) } catch {}
679
- return reply(`⏪ Откачено сообщений: ${res.removed}. Осталось в контексте: ${res.remaining}.`)
680
- }
681
- if (cmd === '/fork') {
682
- const chat = this.chats.get(key)
683
- if (!chat?.agent?.session) {
684
- return reply('Нет активной сессии для форка.')
685
- }
686
- try {
687
- const oldSession = chat.agent.session
688
- const oldMessages = Array.isArray(oldSession.messages)
689
- ? oldSession.messages.map(m => ({ ...m, content: ensureContentArray(m.content) }))
690
- : []
691
- const newChat = await this.createChat(key, input)
692
- if (newChat.agent?.session && oldMessages.length) {
693
- newChat.agent.session.messages = oldMessages
694
- const sessions = this.ctx.get?.('sessions') || this.ctx.sessions
695
- try { await sessions?.flush(newChat.agent.session) } catch {}
696
- }
697
- this.chats.set(key, newChat)
698
- return reply(`🔀 Создан форк сессии!\nСтарая сессия: ${oldSession.id}\nНовая активная сессия: ${newChat.agent.session.id}\nКонтекст сохранён (${oldMessages.length} сообщений).`)
699
- } catch (err) {
700
- return reply(`Ошибка форка: ${err.message}`)
701
- }
702
- }
703
- if (cmd === '/files') {
704
- const subPath = parts.slice(1).join(' ').trim() || '.'
705
- const agentCwd = this.config.agent?.cwd || process.cwd()
706
- const res = await listFiles(agentCwd, subPath)
707
- if (!res.ok) return reply(`❌ ${res.error}`)
708
- return reply(res.formattedText)
709
- }
710
- if (cmd === '/get') {
711
- const targetRel = parts.slice(1).join(' ').trim()
712
- if (!targetRel) {
713
- return reply('Укажите имя файла для скачивания: <code>/get <файл></code>\nСписок: <code>/files</code>')
714
- }
715
- const agentCwd = this.config.agent?.cwd || process.cwd()
716
- const maxDocBytes = Number(this.config.media?.maxDocBytes) || 50 * 1024 * 1024
717
- const res = await getFileForDownload(agentCwd, targetRel, maxDocBytes)
718
- if (!res.ok) return reply(`❌ ${res.error}`)
719
- const file = {
720
- name: res.name,
721
- mime: res.mime,
722
- kind: 'document',
723
- bytes: res.bytes,
724
- dataBase64: res.bytes.toString('base64'),
725
- }
726
- return reply({ text: `📄 Файл: <b>${res.name}</b> (${formatFileSize(res.size)})`, files: [file] })
727
- }
728
- if (cmd === '/new') {
729
- const chat = this.chats.get(key)
730
- if (chat) {
731
- if (chat.abort) chat.abort.abort()
732
- chat.pendingMedia = []
733
- this.sessionToChat.delete(String(chat.agent.session.id))
734
- this.chats.delete(key)
735
- await chat.dispose()
736
- return reply('Сессия сброшена.')
737
- }
738
- return reply('Активной сессии нет.')
739
- }
740
- if (cmd === '/whoami') {
741
- const lines = [`Ваш id: ${userId}`]
742
- if (chatId) lines.push(`chatId: ${chatId}`)
743
- if (threadId) lines.push(`threadId: ${threadId}`)
744
- return reply(lines.join('\n'))
745
- }
746
- if (cmd === '/stop') {
747
- const chat = this.chats.get(key)
748
- if (chat?.turnActive || chat?.abort) {
749
- try { chat.abort?.abort() } catch {}
750
- releaseChatTurn(chat)
751
- chat.turnActive = false
752
- return reply('Прерывание отправлено.')
753
- }
754
- return reply('Нечего прерывать.')
755
- }
756
- if (cmd === '/status') {
757
- let modelLine = 'модель: (не задана)'
758
- try {
759
- const sel = this.resolveAgentModel()
760
- modelLine = `модель: ${sel.provider}/${sel.model}`
761
- } catch (e) {
762
- modelLine = `модель: ${e.message}`
763
- }
764
- const home = this.resolveHomeTarget(platform || 'telegram')
765
- const homeLine = home
766
- ? `home: chat ${home.chatId}${home.threadId ? ` topic ${home.threadId}` : ''}`
767
- : 'home: не задан'
768
- const pending = this.pairing.listPending().length
769
- const up = Math.max(0, Math.round((Date.now() - this.stats.startedAt) / 1000))
770
- const hh = String(Math.floor(up / 3600)).padStart(2, '0')
771
- const mm = String(Math.floor((up % 3600) / 60)).padStart(2, '0')
772
- const ss = String(up % 60).padStart(2, '0')
773
- return reply([
774
- 'Messenger gateway',
775
- `адаптеры: ${[...this.adapters.keys()].join(', ') || '(нет)'}`,
776
- `активных чатов: ${this.chats.size}`,
777
- modelLine,
778
- homeLine,
779
- `pairing pending: ${pending}`,
780
- `transport: ${this.tg().transport || 'poll'}`,
781
- `sessionScope: ${this.config.agent?.sessionScope || 'user'}`,
782
- `доставлено: ${this.stats.sent}`,
783
- `ошибок: ${this.stats.errors}`,
784
- `polling conflict: ${this.tgAdapter?.pollingConflict ? 'да' : 'нет'}`,
785
- `uptime: ${hh}:${mm}:${ss}`,
786
- ].join('\n'))
787
- }
788
- if (cmd === '/model') {
789
- if (parts.length >= 3) {
790
- if (!this.isUserAllowed(userId)) return reply('Нет доступа.')
791
- const provider = parts[1]
792
- const model = parts.slice(2).join(' ')
793
- try {
794
- const adm = this.ctx.get('agentDefaultModel')
795
- if (adm?.saveSelection) {
796
- await adm.saveSelection({ provider, model })
797
- }
798
- this.config.agent = { ...this.config.agent, provider, model }
799
- try {
800
- await this.hooks?.persistAgentModel?.({ provider, model })
801
- } catch (e) {
802
- this.ctx.logger?.warn?.(`persist agent model: ${e.message}`)
803
- }
804
- return reply(`Модель сохранена: ${provider}/${model}`)
805
- } catch (e) {
806
- return reply(`Не удалось сменить модель: ${e.message}`)
807
- }
808
- }
809
- try {
810
- const current = this.resolveAgentModel()
811
- const catalog = await listModelCatalog(this.ctx, current)
812
- if (!catalog.providers.length) {
813
- return reply(`Текущая модель: <code>${current.provider}/${current.model}</code>\nСмена: <code>/model &lt;provider&gt; &lt;model&gt;</code>`)
814
- }
815
- const kb = buildProvidersKeyboard(catalog.providers, current)
816
- return reply([
817
- '🤖 <b>Выберите провайдера:</b>',
818
- `Текущая модель: <code>${current.provider}/${current.model}</code>`,
819
- ].join('\n'), {
820
- replyMarkup: kb,
821
- })
822
- } catch (e) {
823
- return reply(e.message)
824
- }
825
- }
826
- if (cmd === '/pair') {
827
- if (!this.isUserAllowed(userId)) return reply('Только пользователи из allowlist могут одобрять /pair.')
828
- const code = parts[1]
829
- if (!code) return reply('Использование: /pair CODE')
830
- const res = this.pairing.approveCode(code, userId)
831
- if (!res.ok) return reply(`Не удалось: ${res.error}`)
832
- const merged = this.effectiveAllowedIds()
833
- for (const a of this.adapterList) a.setAllowedUserIds?.(merged)
834
- try { await this.hooks?.persistAllowedUserIds?.(merged) } catch (e) {
835
- this.ctx.logger?.warn?.(`persist allowlist: ${e.message}`)
836
- }
837
- return reply(`Одобрен user id ${res.userId}${res.username ? ` (@${res.username})` : ''}.`)
838
- }
839
- if (cmd === '/sethome') {
840
- if (!this.isUserAllowed(userId)) return reply('Нет доступа.')
841
- const name = normalizeHomeName(parts[1] || 'default') || 'default'
842
- try {
843
- const nextTg = upsertHome(this.tg(), { name, chatId, threadId })
844
- await this.hooks?.persistHomes?.(nextTg)
845
- this.config.telegram = nextTg
846
- return reply(`Home «${name}»: chat ${chatId}${threadId ? ` topic ${threadId}` : ''}`)
847
- } catch (e) {
848
- return reply(`Не удалось сохранить home: ${e.message}`)
849
- }
850
- }
851
- if (cmd === '/home') {
852
- const homes = listHomes(this.tg())
853
- if (!homes.length) return reply('Home не задан. /sethome или /sethome name')
854
- return reply(['Homes:', ...homes.map((h) => `• ${h.name}: chat ${h.chatId}${h.threadId ? ` topic ${h.threadId}` : ''}`)].join('\n'))
855
- }
856
- if (cmd === '/setalert') {
857
- if (!this.isUserAllowed(userId)) return reply('Нет доступа.')
858
- const nextTg = {
859
- ...this.tg(),
860
- alerts: {
861
- ...(this.tg().alerts || {}),
862
- enabled: true,
863
- chatId,
864
- threadId: threadId || 0,
865
- },
866
- }
867
- this.config.telegram = nextTg
868
- try { await this.hooks?.persistHomes?.(nextTg) } catch {}
869
- return reply(`🔔 Этот чат назначен каналом алертов (chat: ${chatId}${threadId ? `, topic: ${threadId}` : ''}).`)
870
- }
871
- if (cmd === '/alert') {
872
- const sub = parts[1]?.toLowerCase()
873
- if (sub === 'test') {
874
- const target = resolveAlertTarget(this)
875
- if (!target) return reply('Канал алертов не настроен или выключен. Назначить: /setalert')
876
- await this.sendAlert('status', { title: 'Тестовый алерт', details: `Отправлен пользователем id ${userId}` })
877
- return reply('Тестовый алерт отправлен в канал алертов.')
878
- }
879
- const target = resolveAlertTarget(this)
880
- const alertsCfg = this.tg().alerts || {}
881
- return reply([
882
- '🔔 <b>Канал алертов:</b>',
883
- `Статус: ${alertsCfg.enabled ? 'включен' : 'выключен'}`,
884
- `Чат: ${target ? `${target.chatId}${target.threadId ? ` (topic: ${target.threadId})` : ''}` : '(не назначен)'}`,
885
- `События: ${(alertsCfg.events || ['error', 'pairing']).join(', ')}`,
886
- '',
887
- 'Команды:',
888
- '/setalert назначить текущий чат каналом алертов',
889
- '/alert test отправить тестовый алерт',
890
- ].join('\n'))
891
- }
892
- if (cmd === '/remind') {
893
- const sub = parts[1]?.toLowerCase()
894
- if (sub === 'list') {
895
- const active = await this.scheduler.list(chatId)
896
- if (!active.length) return reply('Нет активных напоминаний для этого чата.')
897
- const lines = [
898
- '⏰ <b>Активные напоминания:</b>',
899
- '',
900
- ...active.map((t) => {
901
- const left = formatRemaining(t.dueAt - Date.now())
902
- return `• <code>${t.id}</code> (через ${left}): ${t.text}`
903
- }),
904
- '',
905
- 'Отмена: <code>/remind cancel ID</code>',
906
- ]
907
- return reply(lines.join('\n'))
908
- }
909
- if (sub === 'cancel') {
910
- const targetId = parts[2]?.trim()
911
- if (!targetId) return reply('Укажите ID напоминания: <code>/remind cancel ID</code>')
912
- const ok = await this.scheduler.cancel(targetId, chatId)
913
- return reply(ok ? `✅ Напоминание <code>${targetId}</code> отменено.` : `❌ Напоминание с ID <code>${targetId}</code> не найдено.`)
914
- }
915
- const timeArg = parts[1]
916
- const textArg = parts.slice(2).join(' ').trim()
917
- const delayMs = parseRelativeTime(timeArg)
918
- if (!delayMs || !textArg) {
919
- return reply([
920
- '⏰ <b>Напоминания:</b>',
921
- 'Создать: <code>/remind &lt;время&gt; &lt;текст&gt;</code>',
922
- 'Примеры: <code>/remind 10m Позвонить</code>, <code>/remind 2h Проверить деплой</code>',
923
- 'Список: <code>/remind list</code>',
924
- 'Отмена: <code>/remind cancel ID</code>',
925
- ].join('\n'))
926
- }
927
- const dueAt = Date.now() + delayMs
928
- const task = await this.scheduler.schedule({
929
- platform: platform || 'telegram',
930
- chatId,
931
- threadId: threadId || 0,
932
- userId,
933
- text: textArg,
934
- dueAt,
935
- })
936
- const left = formatRemaining(delayMs)
937
- return reply(`⏰ Напоминание установлено на <b>через ${left}</b> (ID: <code>${task.id}</code>):\n«${textArg}»`)
938
- }
939
- if (cmd === '/voice') {
940
- const sub = String(parts[1] || 'status').toLowerCase()
941
- if (sub === 'summary') {
942
- const val = parts[2]?.toLowerCase()
943
- if (val === 'on' || val === 'off') {
944
- if (!this.config.tts) this.config.tts = {}
945
- this.config.tts.voiceSummary = val === 'on'
946
- return reply(`Голосовое саммари (TL;DR): ${val === 'on' ? 'включено' : 'выключено'}`)
947
- }
948
- const state = this.config.tts?.voiceSummary ? 'on' : 'off'
949
- return reply(`Голосовое саммари (TL;DR): ${state}\nПереключение: <code>/voice summary on|off</code>`)
950
- }
951
- if (sub === 'on' || sub === 'off') {
952
- this.voicePrefs.set(userId, sub === 'on')
953
- return reply(sub === 'on' ? 'Голосовые ответы: on (для вас)' : 'Голосовые ответы: off (для вас)')
954
- }
955
- const pref = this.voicePrefs.get(userId)
956
- const mode = this.tg().voiceMode || 'mirror'
957
- const prefLine = pref === null ? 'не задан (/voice on|off)' : (pref ? 'on' : 'off')
958
- const summaryState = this.config.tts?.voiceSummary ? 'on' : 'off'
959
- return reply(`voiceMode=${mode}\nваш /voice: ${prefLine}\nglobal tts: ${this.config.tts?.enabled ? 'on' : 'off'}\nvoice summary: ${summaryState}`)
960
- }
961
- if (cmd === '/topic') {
962
- const topicName = parts.slice(1).join(' ').trim()
963
- if (!topicName) {
964
- return reply('Использование: <code>/topic &lt;название&gt;</code>\nСоздает новый топик в супергруппе и изолированную сессию под задачу.')
965
- }
966
- const tgAdapter = this.getAdapter('telegram')
967
- if (!tgAdapter?.createForumTopic) {
968
- return reply('Создание топиков доступно только в Telegram.')
969
- }
970
- try {
971
- const res = await tgAdapter.createForumTopic(chatId, topicName)
972
- const newThreadId = res?.message_thread_id
973
- await reply(`🎯 Создан новый топик <b>«${topicName}»</b> (ID: <code>${newThreadId}</code>).\nПерейдите в созданный топик для работы над задачей!`)
974
- if (newThreadId) {
975
- await tgAdapter.sendTo(chatId, {
976
- text: `👋 Привет! Это изолированная сессия для задачи <b>«${topicName}»</b>.\nЧем могу помочь?`,
977
- }, { threadId: newThreadId })
978
- }
979
- return
980
- } catch (err) {
981
- return reply(`Не удалось создать топик: ${err.message}\n(Убедитесь, что бот является администратором группы и включены темы/форумы)`)
982
- }
983
- }
984
- if (cmd === '/top') {
985
- const mem = process.memoryUsage()
986
- const rssMb = (mem.rss / 1024 / 1024).toFixed(1)
987
- const heapMb = (mem.heapUsed / 1024 / 1024).toFixed(1)
988
- const sec = Math.floor((Date.now() - this.stats.startedAt) / 1000)
989
- const hh = String(Math.floor(sec / 3600)).padStart(2, '0')
990
- const mm = String(Math.floor((sec % 3600) / 60)).padStart(2, '0')
991
- const ss = String(sec % 60).padStart(2, '0')
992
- let activeReminders = 0
993
- try { activeReminders = (await this.scheduler.list()).length } catch {}
994
- let currentModel = 'не задана'
995
- try {
996
- const m = this.resolveAgentModel()
997
- currentModel = `${m.provider}/${m.model}`
998
- } catch {}
999
-
1000
- return reply([
1001
- '📊 <b>DSH System & Resources:</b>',
1002
- `• <b>Память (RSS):</b> ${rssMb} MB`,
1003
- `• <b>Heap:</b> ${heapMb} MB`,
1004
- `• <b>Аптайм:</b> ${hh}:${mm}:${ss}`,
1005
- `• <b>Активных чатов:</b> ${this.chats.size}`,
1006
- `• <b>Напоминаний в очереди:</b> ${activeReminders}`,
1007
- `• <b>Активная модель:</b> <code>${currentModel}</code>`,
1008
- `• <b>Сообщений отправлено:</b> ${this.stats.sent}`,
1009
- `• <b>Ошибок:</b> ${this.stats.errors}`,
1010
- ].join('\n'))
1011
- }
1012
- if (cmd === '/keyboard') {
1013
- const sub = String(parts[1] || '').toLowerCase()
1014
- const tgAdapter = this.getAdapter('telegram')
1015
- if (sub === 'on') {
1016
- if (tgAdapter) tgAdapter.quickActions = true
1017
- return reply('Клавиатура быстрых действий включена.', {
1018
- replyMarkup: buildQuickActionsKeyboard(),
1019
- })
1020
- }
1021
- if (sub === 'off') {
1022
- if (tgAdapter) tgAdapter.quickActions = false
1023
- return reply('Клавиатура быстрых действий выключена.', {
1024
- replyMarkup: REMOVE_REPLY_KEYBOARD,
1025
- })
1026
- }
1027
- const curState = tgAdapter?.quickActions ? 'включена' : 'выключена'
1028
- return reply([
1029
- '⌨️ <b>Клавиатура быстрых действий:</b>',
1030
- `Текущее состояние: <b>${curState}</b>`,
1031
- '',
1032
- 'Команды:',
1033
- '<code>/keyboard on</code> показать кнопки',
1034
- '<code>/keyboard off</code> скрыть кнопки',
1035
- ].join('\n'))
1036
- }
1037
- if (cmd === '/tts') {
1038
- const sub = String(parts[1] || 'status').toLowerCase()
1039
- if (sub === 'on' || sub === 'off') {
1040
- this.chatTts.set(chatId, sub === 'on')
1041
- return reply(sub === 'on' ? 'Озвучка в этом чате: on' : 'Озвучка в этом чате: off')
1042
- }
1043
- const cur = this.chatTts.get(chatId)
1044
- const line = cur === null ? 'не задан (/tts on|off)' : (cur ? 'on' : 'off')
1045
- return reply(`Озвучка в этом чате: ${line}\nglobal tts: ${this.config.tts?.enabled ? 'on' : 'off'}`)
1046
- }
1047
- if (cmd === '/mute') {
1048
- this.setMuted(chatId, true)
1049
- return reply('Уведомления в этот чат: выключены (/unmute)')
1050
- }
1051
- if (cmd === '/unmute') {
1052
- this.setMuted(chatId, false)
1053
- return reply('Уведомления в этот чат: включены')
1054
- }
1055
- return reply(`Неизвестная команда ${cmd}. /help`)
1056
- }
1057
-
1058
- async getOrCreateChat(key, input) {
1059
- let chat = this.chats.get(key)
1060
- if (!chat) { chat = await this.createChat(key, input); this.chats.set(key, chat) }
1061
- chat.lastUsed = Date.now()
1062
- chat.target = { platform: input.platform, chatId: input.chatId, threadId: input.threadId || 0 }
1063
- return chat
1064
- }
1065
-
1066
- resolveAgentModel() {
1067
- const agentCfg = this.config.agent || {}
1068
- let provider = String(agentCfg.provider || '').trim()
1069
- let model = String(agentCfg.model || '').trim()
1070
- if (provider && model) return { provider, model }
1071
- const selection = this.ctx.get('agentDefaultModel')?.currentSelection?.()
1072
- if (!selection?.provider || !selection?.model) {
1073
- throw new Error('Выберите модель в Settings → Models (или укажите agent.provider/model в профиле)')
1074
- }
1075
- return { provider: provider || selection.provider, model: model || selection.model }
1076
- }
1077
-
1078
- async createChat(key, input) {
1079
- const { provider, model } = this.resolveAgentModel()
1080
- const agentCfg = this.config.agent || {}
1081
- const cwd = agentCfg.cwd || process.cwd()
1082
- const self = this
1083
- const agents = this.ctx.get?.('agents') || this.ctx.agents
1084
- const handle = await agents.create({
1085
- sessionId: SessionId(`msgw-${randomUUID()}`),
1086
- meta: { cwd },
1087
- agentOptions: { provider, model },
1088
- setup: (agentCtx) => {
1089
- installModelSelection(agentCtx, { current: { provider, model }, assembled: undefined })
1090
- if (self.tg().approvalsEnabled !== false) {
1091
- agentCtx.on('approval/request', (req, next) => self.answerApproval(key, req, next))
1092
- }
1093
- },
1094
- })
1095
- await handle.agent.whenIdle()
1096
- const chat = {
1097
- key, agent: handle.agent, dispose: handle.dispose, busy: Promise.resolve(),
1098
- lastUsed: Date.now(), abort: undefined, pendingMedia: [], turnActive: false,
1099
- target: input ? { platform: input.platform, chatId: input.chatId, threadId: input.threadId || 0 } : undefined,
1100
- }
1101
- this.sessionToChat.set(String(handle.agent.session.id), key)
1102
- return chat
1103
- }
1104
-
1105
- async answerApproval(chatKeyValue, req, next) {
1106
- try {
1107
- const chat = this.chats.get(chatKeyValue)
1108
- if (!chat?.target) return next()
1109
- const tool = req.toolName || 'tool'
1110
- const reason = req.reason ? `\n${req.reason}` : ''
1111
- const result = await this.messengerAsk(chat.target, {
1112
- text: `⚠️ Нужно подтверждение\nИнструмент: ${tool}${reason}`,
1113
- buttons: [[{ id: 'allow', text: '✅ Разрешить' }, { id: 'deny', text: '❌ Отклонить' }]],
1114
- }, 300_000)
1115
- if (result?.buttonId === 'allow') return 'allowed-once'
1116
- if (result?.buttonId === 'deny') return 'rejected'
1117
- return next()
1118
- } catch {
1119
- return next()
1120
- }
1121
- }
1122
-
1123
- async buildUserContent(input, signal) {
1124
- const { text, attachments = [], replyText, steer, personaOverride } = input
1125
- const parts = []
1126
- parts.push(String(this.config.agent?.instructionPrefix || MESSENGER_RELAY_INSTRUCTION))
1127
- const activePersonaId = personaOverride || this.personas.get(input.chatId)
1128
- const activePersona = getPersona(activePersonaId)
1129
- if (activePersona?.instruction) {
1130
- parts.push(`[Persona: ${activePersona.name} (${activePersona.icon})]\n${activePersona.instruction}`)
1131
- }
1132
- if (steer) parts.push('[Steer / дополнение к текущему ходу — учти вместе с предыдущим запросом, не начинай ответ заново с нуля]')
1133
- if (replyText?.trim()) parts.push(`[Ответ на сообщение: ${replyText.trim()}]`)
1134
- const blocks = []
1135
- for (const att of attachments) {
1136
- if (att.kind === 'photo' || (att.kind === 'sticker' && att.mime?.startsWith('image/'))) {
1137
- try {
1138
- const { ref } = await attachInboundPhoto(this.ctx, att, {
1139
- signal,
1140
- maxBytes: Number(this.config.media?.maxImageBytes) || 20 * 1024 * 1024,
1141
- })
1142
- blocks.push({ type: 'image', attachment: ref })
1143
- if (att.kind === 'sticker' && att.emoji) parts.push(`[Стикер ${att.emoji}]`)
1144
- } catch (err) {
1145
- if (signal?.aborted) throw err
1146
- const msg = err instanceof Error ? err.message : String(err)
1147
- parts.push(`[Не удалось приложить изображение: ${msg}]`)
1148
- }
1149
- } else if (att.kind === 'voice' || att.kind === 'audio') {
1150
- try {
1151
- const bytes = new Uint8Array(await readFile(att.path))
1152
- const transcript = await transcribeVoice(this.baseUrl(), bytes, att.mime || 'audio/ogg', 'message', signal)
1153
- parts.push(transcript ? `[Голосовое сообщение, расшифровка: ${transcript}]` : '[Голосовое сообщение (не удалось распознать)]')
1154
- } catch (err) {
1155
- if (signal?.aborted) throw err
1156
- const msg = err instanceof Error ? err.message : String(err)
1157
- this.ctx.logger?.warn?.(`voice: ${msg}`)
1158
- parts.push(`[Голосовое сообщение (dsh-voice недоступен: ${msg})]`)
1159
- }
1160
- } else if (att.kind === 'document' || att.kind === 'video' || att.kind === 'animation' || att.kind === 'sticker') {
1161
- let parsed = null
1162
- if (att.kind === 'document' && att.path) {
1163
- try {
1164
- const maxDocBytes = Number(this.config.media?.maxTextInjectBytes) || 100 * 1024
1165
- parsed = await parseDocument(att.path, { maxBytes: maxDocBytes })
1166
- } catch {}
1167
- }
1168
- parts.push(formatInboundDocument(att, parsed))
1169
- } else {
1170
- parts.push(`[Файл: ${att.path}${att.name ? ` (${att.name})` : ''}]`)
1171
- }
1172
- }
1173
- const photoHint = photoOnlyHint(attachments, text)
1174
- if (photoHint) parts.push(photoHint)
1175
- const docHint = documentOnlyHint(attachments, text)
1176
- if (docHint) parts.push(docHint)
1177
- if (text?.trim()) parts.push(text.trim())
1178
- const textBlock = parts.filter(Boolean).join('\n\n')
1179
- if (textBlock) blocks.unshift({ type: 'text', text: textBlock })
1180
- if (!blocks.length) blocks.push({ type: 'text', text: '(пустое сообщение)' })
1181
- return blocks
1182
- }
1183
-
1184
- async runTurn(chat, input, signal) {
1185
- const { reply, typing, startStream, startProgress, react, inboundWasVoice, userId } = input
1186
- chat.turnActive = true
1187
- const sessionId = chat.agent.session.id
1188
- const tg = this.tg()
1189
- const streaming = tg.streaming === true && typeof startStream === 'function'
1190
- const progressEnabled = tg.progressEnabled !== false
1191
- const collector = { parts: [], lastText: '', streamText: '', toolName: '', images: [], reason: undefined, onStream: undefined }
1192
- this.pending.set(sessionId, collector)
1193
- let stopTyping = () => {}
1194
- let stream = null
1195
- let scheduler = null
1196
- let progress = null
1197
- try {
1198
- if (signal.aborted) return
1199
- if (typeof react === 'function' && tg.reactionsEnabled !== false) {
1200
- react('👀').catch?.(() => {})
1201
- }
1202
- if (typeof typing === 'function') stopTyping = startTypingHeartbeat(typing, 4000)
1203
- if (streaming) {
1204
- try {
1205
- stream = await startStream()
1206
- scheduler = createEditScheduler((text) => stream.edit(text), Number(tg.streamEditIntervalMs) || 1200)
1207
- collector.onStream = (text, toolName) => {
1208
- if (text) stopTyping()
1209
- if (!progressEnabled && !text) return
1210
- scheduler.push(buildStreamPreview(text, progressEnabled ? toolName : ''))
1211
- }
1212
- if (progressEnabled) scheduler.push(buildStreamPreview('', ''))
1213
- } catch (e) {
1214
- this.ctx.logger?.warn?.(`stream start: ${e.message}`)
1215
- stream = null
1216
- }
1217
- } else if (progressEnabled && typeof startProgress === 'function') {
1218
- try {
1219
- progress = await startProgress()
1220
- const editProgress = createEditScheduler((text) => progress.edit(text), 800)
1221
- collector.onStream = (_text, toolName) => {
1222
- editProgress.push(formatProgressLine(toolName))
1223
- }
1224
- } catch (e) {
1225
- this.ctx.logger?.warn?.(`progress start: ${e.message}`)
1226
- progress = null
1227
- }
1228
- }
1229
-
1230
-
1231
- const content = await this.buildUserContent(input, signal)
1232
- chat.agent.followup(createUserMessage({
1233
- content: ensureContentArray(content),
1234
- source: { kind: 'plugin', plugin: PLUGIN, form: 'relay' },
1235
- }))
1236
- const turnTimeoutMs = Number(this.config.agent?.turnTimeoutMs) || 600_000
1237
- await whenIdleWithTimeout(chat.agent, turnTimeoutMs, signal)
1238
- if (signal.aborted) {
1239
- if (progress) try { await progress.remove() } catch {}
1240
- if (typeof react === 'function') react('').catch?.(() => {})
1241
- if (stream) try { await stream.finalize('Прервано.') } catch {}
1242
- else return reply('Прервано.')
1243
- return
1244
- }
1245
- const sessions = this.ctx.get?.('sessions') || this.ctx.sessions
1246
- await sessions?.flush?.(chat.agent.session)
1247
- if (progress) try { await progress.remove() } catch {}
1248
- progress = null
1249
- if (typeof react === 'function') react('').catch?.(() => {})
1250
- const rawAnswer = stripReasoningPreamble(stripImageUrls(collector.lastText || collector.streamText || collector.parts.join('\n\n')))
1251
- const processed = processDiagramsAndTables(rawAnswer, {
1252
- artifactPreviews: this.tg().artifactPreviews !== false,
1253
- })
1254
- const answer = processed.text
1255
- if (collector.reason?.kind === 'error') {
1256
- const err = collector.reason.error
1257
- const msg = `Ошибка агента: ${err?.code || 'error'}: ${err?.message || 'unknown'}`
1258
- this.sendAlert('error', {
1259
- code: err?.code || 'AGENT_ERROR',
1260
- message: err?.message || 'unknown',
1261
- sessionId,
1262
- chatId: input.chatId,
1263
- threadId: input.threadId,
1264
- }).catch(() => {})
1265
- if (stream) { await scheduler?.flush(); await stream.finalize(msg) }
1266
- else await reply(msg)
1267
- return
1268
- }
1269
- const files = await buildOutboundFiles(this.ctx, this.baseUrl(), collector, { signal, logger: this.ctx.logger })
1270
- const allFiles = [...files, ...(processed.files || [])]
1271
- if (!answer && !allFiles.length) {
1272
- if (stream) { await scheduler?.flush(); await stream.finalize('(нет ответа)') }
1273
- else await reply('(нет ответа)')
1274
- return
1275
- }
1276
- const maxLen = Number(this.config.agent?.maxMessageLength) || 4000
1277
- const chunks = answer ? splitText(answer, maxLen) : ['']
1278
- if (stream) {
1279
- await scheduler?.flush()
1280
- await stream.finalize(chunks[0] || '(нет ответа)')
1281
- for (let i = 1; i < chunks.length; i++) await reply({ text: chunks[i] })
1282
- if (allFiles.length) await reply({ files: allFiles })
1283
- } else {
1284
- for (let i = 0; i < chunks.length; i++) {
1285
- await reply({ text: chunks[i] || undefined, files: i === 0 ? allFiles : [] })
1286
- }
1287
- }
1288
- const chatTtsPref = this.chatTts.get(chat.target?.chatId)
1289
- const speak = shouldSpeakReply({
1290
- globalTts: Boolean(this.config.tts?.enabled),
1291
- voiceMode: this.tg().voiceMode || 'mirror',
1292
- inboundWasVoice: Boolean(inboundWasVoice),
1293
- userPref: this.voicePrefs.get(userId),
1294
- chatPref: chatTtsPref,
1295
- })
1296
- if (speak && !signal.aborted) {
1297
- const isVoiceSummary = this.config.tts?.voiceSummary === true
1298
- const ttsText = prepareTtsText(answer, this.config.tts?.maxChars, { voiceSummary: isVoiceSummary })
1299
- if (ttsText) {
1300
- try {
1301
- const spoken = await speakText(this.baseUrl(), ttsText, signal)
1302
- const voiceFile = await toTelegramVoiceFile(spoken, { logger: this.ctx.logger })
1303
- if (!signal.aborted && voiceFile) await reply({ files: [voiceFile] })
1304
- } catch (e) {
1305
- if (!signal?.aborted) this.ctx.logger?.warn?.(`tts: ${e.message}`)
1306
- }
1307
- }
1308
- }
1309
- } catch (err) {
1310
- if (!signal?.aborted) {
1311
- this.sendAlert('error', {
1312
- code: err?.code || 'EXCEPTION',
1313
- message: err?.message || String(err),
1314
- sessionId,
1315
- chatId: input.chatId,
1316
- threadId: input.threadId,
1317
- }).catch(() => {})
1318
- try {
1319
- if (stream) await stream.finalize(`Сбой: ${err.message}`)
1320
- else await reply(`Сбой: ${err.message}`)
1321
- } catch {}
1322
- }
1323
- } finally {
1324
- stopTyping()
1325
- if (progress) try { await progress.remove() } catch {}
1326
- if (typeof react === 'function') react('').catch?.(() => {})
1327
- chat.turnActive = false
1328
- chat.abort = undefined
1329
- this.pending.delete(sessionId)
1330
- }
1331
- }
1332
-
1333
- reapIdle() {
1334
- const rawTimeout = Number(this.config.agent?.idleTimeoutMs)
1335
- const timeout = Number.isFinite(rawTimeout) && rawTimeout > 0 ? rawTimeout : 86_400_000
1336
- const now = Date.now()
1337
- for (const [key, chat] of this.chats) {
1338
- if (!chat.turnActive && now - chat.lastUsed > timeout) {
1339
- if (chat.agent?.session?.id) {
1340
- this.sessionToChat.delete(String(chat.agent.session.id))
1341
- }
1342
- this.chats.delete(key)
1343
- chat.dispose().catch(() => {})
1344
- }
1345
- }
1346
- }
1347
-
1348
- async approvePairingCode(code, actorUserId = 0) {
1349
- const res = this.pairing.approveCode(code, actorUserId)
1350
- if (!res.ok) return res
1351
- const merged = this.effectiveAllowedIds()
1352
- for (const a of this.adapterList) a.setAllowedUserIds?.(merged)
1353
- try { await this.hooks?.persistAllowedUserIds?.(merged) } catch (e) {
1354
- this.ctx.logger?.warn?.(`persist allowlist: ${e.message}`)
1355
- }
1356
- return { ...res, allowedUserIds: merged }
1357
- }
1358
-
1359
- rejectPairingCode(code) {
1360
- return this.pairing.rejectCode(code)
1361
- }
1362
-
1363
- async probeTelegram(timeoutMs = 10000) {
1364
- const adapter = this.getAdapter('telegram')
1365
- if (!adapter) {
1366
- return { ok: false, error: 'Telegram adapter not initialized' }
1367
- }
1368
- if (typeof adapter.probeHealth === 'function') {
1369
- return adapter.probeHealth(timeoutMs)
1370
- }
1371
- return { ok: false, error: 'probeHealth not implemented on adapter' }
1372
- }
1373
-
1374
- getBotInfo() {
1375
- const adapter = this.getAdapter('telegram')
1376
- return {
1377
- botId: adapter?.botId || 0,
1378
- botUsername: adapter?.botUsername || '',
1379
- pollingConflict: Boolean(adapter?.pollingConflict),
1380
- }
1381
- }
1382
-
1383
- async messengerAskFromAgent(agent, payload, timeoutMs) {
1384
- const sessionId = String(agent?.session?.id || '')
1385
- const key = this.sessionToChat.get(sessionId)
1386
- const chat = key ? this.chats.get(key) : null
1387
- if (!chat?.target) throw new Error('messenger_ask: no telegram chat for this agent session')
1388
- return this.messengerAsk(chat.target, payload, timeoutMs)
1389
- }
1390
-
1391
- get messenger() {
1392
- return {
1393
- adapters: () => [...this.adapters.keys()],
1394
- activeChats: () => this.chats.size,
1395
- home: (name) => this.resolveHomeTarget('telegram', name),
1396
- homes: () => listHomes(this.tg()),
1397
- pairingPending: () => this.pairing.listPending(),
1398
- pairingApproved: () => this.pairing.listApproved(),
1399
- send: (target, payload) => this.messengerSend(target, payload),
1400
- ask: (target, payload, timeoutMs) => this.messengerAsk(target, payload, timeoutMs),
1401
- progress: (target, payload) => this.messengerProgress(target, payload),
1402
- probeTelegram: (timeoutMs) => this.probeTelegram(timeoutMs),
1403
- getBotInfo: () => this.getBotInfo(),
1404
- }
1405
- }
1406
- }
1
+ import { readFile } from 'node:fs/promises'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { join } from 'node:path'
4
+ import { homedir } from 'node:os'
5
+ import { installModelSelection } from '@deepseek-ai/dsh-agent'
6
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
7
+ import { SessionId } from '@deepseek-ai/dsh-session'
8
+ import createAdapters from './adapters/index.js'
9
+ import { transcribeVoice, speakText } from './integrations.js'
10
+ import { attachInboundPhoto, photoOnlyHint } from './photos.js'
11
+ import { formatInboundDocument, documentOnlyHint, parseDocument } from './documents.js'
12
+ import { listFiles, getFileForDownload, formatFileSize } from './file-manager.js'
13
+ import { collectAssistantParts, buildOutboundFiles, stripImageUrls } from './outbound.js'
14
+ import { assistantText, splitText, stripReasoningPreamble, MESSENGER_RELAY_INSTRUCTION } from './text.js'
15
+ import { chatKey, sessionKey } from './topics.js'
16
+ import { listHomes, resolveNamedHome, upsertHome, normalizeHomeName } from './homes.js'
17
+ import { createVoicePrefs, shouldSpeakReply } from './voice-prefs.js'
18
+ import { prepareTtsText, toTelegramVoiceFile } from './tts.js'
19
+ import {
20
+ makeAskToken, buildInlineKeyboard, buildMultiSelectKeyboard, indexCallbacks, releaseCallbacks,
21
+ parseCallbackData, parseAskCallback, targetMatchesAsk, rejectPendingAsk, REMOVE_KEYBOARD,
22
+ } from './ask.js'
23
+ import { processDiagramsAndTables } from './artifacts.js'
24
+ import { createPersonaStore, getPersona, listPersonas, BUILTIN_PERSONAS } from './personas.js'
25
+ import { exportSessionToMarkdown, rewindSession } from './session-ops.js'
26
+ import { formatAlertMessage, resolveAlertTarget } from './alerts.js'
27
+ import { createScheduler, parseRelativeTime, formatRemaining } from './scheduler.js'
28
+ import { listModelCatalog, buildProvidersKeyboard, buildModelsKeyboard, getStoredModelSelection } from './models.js'
29
+ import { buildQuickActionsKeyboard, REMOVE_REPLY_KEYBOARD } from './adapters/telegram.js'
30
+ import { createPairingStore } from './pairing.js'
31
+ import {
32
+ extractTextDelta, extractToolName, buildStreamPreview, formatProgressLine,
33
+ createEditScheduler, startTypingHeartbeat,
34
+ } from './stream.js'
35
+ import { isTopicGoneError } from './telegram-errors.js'
36
+ import { ensureContentArray } from './content-guard.js'
37
+ import { mergeDynamicCommands } from './commands.js'
38
+ import { t } from './locales/index.js'
39
+
40
+
41
+ function whenIdleWithTimeout(agent, timeoutMs, signal) {
42
+ const idle = agent.whenIdle()
43
+ if (!timeoutMs || timeoutMs <= 0) return idle
44
+ return Promise.race([
45
+ idle,
46
+ new Promise((_, reject) => {
47
+ const timer = setTimeout(() => reject(new Error(`turn timeout (${timeoutMs}ms)`)), timeoutMs)
48
+ timer.unref?.()
49
+ signal?.addEventListener('abort', () => { clearTimeout(timer); reject(new DOMException('Aborted', 'AbortError')) }, { once: true })
50
+ }),
51
+ ])
52
+ }
53
+
54
+ function releaseChatTurn(chat) {
55
+ chat.busy = Promise.resolve()
56
+ }
57
+
58
+ const PLUGIN = 'dsh-messenger-gateway'
59
+
60
+ export class Gateway {
61
+ constructor(ctx, config, hooks = {}) {
62
+ this.ctx = ctx
63
+ this.config = config
64
+ this.hooks = hooks
65
+ this.chats = new Map()
66
+ this.sessionToChat = new Map()
67
+ this.sessionToThread = new Map()
68
+ this.threadToSession = new Map()
69
+ this.pending = new Map()
70
+ this.pendingAsks = new Map()
71
+ this.adapters = new Map()
72
+ this.adapterList = []
73
+ this.disposeListener = undefined
74
+ this.idleTimer = undefined
75
+ this.callbackIndex = new Map()
76
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh')
77
+ this.pairing = createPairingStore(join(home, 'messenger-gateway', 'pairing.json'))
78
+ this.voicePrefs = createVoicePrefs(join(home, 'messenger-gateway', 'voice-prefs.json'))
79
+ this.chatTts = createVoicePrefs(join(home, 'messenger-gateway', 'chat-tts.json'))
80
+ this.muted = createVoicePrefs(join(home, 'messenger-gateway', 'muted.json'))
81
+ this.personas = createPersonaStore(join(home, 'messenger-gateway', 'personas.json'))
82
+ this.chatLocales = createVoicePrefs(join(home, 'messenger-gateway', 'chat-locales.json'))
83
+ this.scheduler = createScheduler(join(home, 'messenger-gateway', 'scheduled.json'), async (task) => {
84
+ const target = {
85
+ platform: task.platform || 'telegram',
86
+ chatId: task.chatId,
87
+ threadId: task.threadId || 0,
88
+ }
89
+ const locale = this.resolveLocale({ chatId: task.chatId })
90
+ if (task.prompt || task.action === 'prompt') {
91
+ const promptText = task.prompt || task.text
92
+ try {
93
+ await this.dispatchAutonomousPrompt(target, promptText, locale)
94
+ } catch (err) {
95
+ const msg = err instanceof Error ? err.message : String(err)
96
+ this.ctx.logger?.warn?.(`dsh-messenger-gateway: cron prompt error: ${msg}`)
97
+ await this.sendToMessenger(target, {
98
+ text: `⚠️ <b>[Cron Error]</b>\n${msg}`,
99
+ }).catch(() => {})
100
+ }
101
+ } else {
102
+ const text = t('remind.prefix', { text: task.text }, locale)
103
+ await this.sendToMessenger(target, { text })
104
+ }
105
+ })
106
+ this.stats = { sent: 0, errors: 0, startedAt: Date.now() }
107
+ }
108
+
109
+ resolveLocale(input) {
110
+ if (input?.locale) return input.locale
111
+ const chatId = input?.chatId
112
+ if (chatId && this.chatLocales?.get(chatId)) return this.chatLocales.get(chatId)
113
+ if (input?.languageCode) {
114
+ const code = String(input.languageCode).toLowerCase()
115
+ if (code.startsWith('zh')) return 'zh'
116
+ if (code.startsWith('en')) return 'en'
117
+ }
118
+ return this.config?.defaultLocale || 'en'
119
+ }
120
+
121
+ async dispatchAutonomousPrompt(target, promptText, locale = 'en') {
122
+ const key = this.sessionKeyFor(target)
123
+ const reply = async (payload) => {
124
+ await this.sendToMessenger(target, typeof payload === 'string' ? { text: payload } : payload)
125
+ }
126
+ const input = {
127
+ platform: target.platform || 'telegram',
128
+ chatId: target.chatId,
129
+ threadId: target.threadId || 0,
130
+ text: promptText,
131
+ reply,
132
+ locale,
133
+ }
134
+ const chat = await this.getOrCreateChat(key, input)
135
+ const turnInput = { ...input, attachments: [], inboundWasVoice: false }
136
+ chat.turnActive = true
137
+ try { chat.abort?.abort?.() } catch {}
138
+ chat.abort = new AbortController()
139
+ const run = chat.busy.then(() => this.runTurn(chat, turnInput, chat.abort.signal))
140
+ chat.busy = run.catch(() => {})
141
+ run.catch((err) => {
142
+ const msg = err instanceof Error ? err.message : String(err)
143
+ this.ctx.logger?.warn?.(`dsh-messenger-gateway: cron turn: ${msg}`)
144
+ chat.turnActive = false
145
+ chat.abort = undefined
146
+ })
147
+ return run
148
+ }
149
+
150
+ isMuted(chatId) { return this.muted.get(chatId) === true }
151
+ setMuted(chatId, on) { return this.muted.set(chatId, on) }
152
+
153
+ baseUrl() {
154
+ const raw = String(this.config.internalBaseURL || '').trim()
155
+ return raw || 'http://127.0.0.1:3080'
156
+ }
157
+
158
+ tg() { return this.config.telegram || {} }
159
+
160
+ effectiveAllowedIds() {
161
+ const fromConfig = (this.tg().allowedUserIds || []).map(Number).filter(Number.isFinite)
162
+ const fromPairing = this.pairing.listApproved()
163
+ return [...new Set([...fromConfig, ...fromPairing])]
164
+ }
165
+
166
+ isUserAllowed(userId) {
167
+ const ids = this.effectiveAllowedIds()
168
+ return ids.length === 0 || ids.includes(Number(userId))
169
+ }
170
+
171
+ resolveHomeTarget(platform = 'telegram', name) {
172
+ const tg = this.tg()
173
+ const home = resolveNamedHome(tg, name)
174
+ if (!home) return null
175
+ const out = { platform, chatId: home.chatId, homeName: home.name }
176
+ if (home.threadId > 0) out.threadId = home.threadId
177
+ return out
178
+ }
179
+
180
+ async sendAlert(type, payload = {}) {
181
+ try {
182
+ const target = resolveAlertTarget(this)
183
+ if (!target) return
184
+ const allowedEvents = this.config.telegram?.alerts?.events || ['error', 'pairing']
185
+ if (type !== 'status' && !allowedEvents.includes(type)) return
186
+
187
+ const text = formatAlertMessage(type, payload)
188
+ await this.sendToMessenger(target, { text })
189
+ } catch (err) {
190
+ this.ctx.logger?.warn?.(`sendAlert (${type}): ${err.message}`)
191
+ }
192
+ }
193
+
194
+ async start() {
195
+ this.disposeListener = this.ctx.on('session/event', (session, event) => {
196
+ if (this.config.telegram?.forumMirrorEnabled) {
197
+ if (event.type === 'turn/start' || event.type === 'session/create') {
198
+ this.mirrorSessionToForumTopic(session).catch?.(() => {})
199
+ } else if (event.type === 'turn/end') {
200
+ this.relayTurnToForumMirror(session, event).catch?.(() => {})
201
+ }
202
+ }
203
+
204
+ const collector = this.pending.get(session.id)
205
+ if (!collector) return
206
+ if (event.type === 'assistant/message') {
207
+ const msg = event.data.message
208
+ const text = assistantText(msg)
209
+ if (text) collector.lastText = text
210
+ const extra = collectAssistantParts(msg)
211
+ for (const img of extra.images) collector.images.push(img)
212
+ } else if (event.type === 'assistant/chunk') {
213
+ const delta = extractTextDelta(event.data?.chunk)
214
+ if (delta) {
215
+ collector.streamText = (collector.streamText || '') + delta
216
+ collector.onStream?.(collector.streamText, collector.toolName)
217
+ }
218
+ } else if (event.type === 'tool/call') {
219
+ collector.toolName = extractToolName(event.data) || collector.toolName
220
+ collector.onStream?.(collector.streamText || '', collector.toolName)
221
+ } else if (event.type === 'tool/result') {
222
+ collector.toolName = ''
223
+ collector.onStream?.(collector.streamText || '', '')
224
+ } else if (event.type === 'turn/end') {
225
+ collector.reason = event.data.reason
226
+ }
227
+ })
228
+ const adapters = createAdapters({
229
+ config: this.config,
230
+ onMessage: (input) => this.handleMessage(input),
231
+ onCallback: (cb) => this.handleCallback(cb),
232
+ onUnauthorized: (input) => this.handleUnauthorized(input),
233
+ isUserAllowed: (id) => this.isUserAllowed(id),
234
+ logger: this.ctx.logger,
235
+ })
236
+ for (const adapter of adapters) {
237
+ try {
238
+ await adapter.start()
239
+ this.adapterList.push(adapter)
240
+ this.adapters.set(adapter.name, adapter)
241
+ if (adapter.name === 'telegram') this.tgAdapter = adapter
242
+ this.ctx.logger?.info?.(`dsh-messenger-gateway: ${adapter.name} started`)
243
+ } catch (err) {
244
+ this.ctx.logger?.warn?.(`dsh-messenger-gateway: ${adapter.name}: ${err.message}`)
245
+ }
246
+ }
247
+ if (this.adapters.has('telegram')) {
248
+ await this.syncTelegramCommands().catch((err) => {
249
+ this.ctx.logger?.warn?.(`Initial syncTelegramCommands: ${err?.message || err}`)
250
+ })
251
+ }
252
+ const rawIdle = Number(this.config.agent?.idleTimeoutMs)
253
+ const idleMs = Number.isFinite(rawIdle) && rawIdle > 0 ? rawIdle : 86_400_000
254
+ this.idleTimer = setInterval(() => this.reapIdle(), Math.min(idleMs, 60_000))
255
+ this.idleTimer.unref?.()
256
+ this.scheduler.start()
257
+ }
258
+
259
+ stop() {
260
+ if (this.scheduler) this.scheduler.stop()
261
+ if (this.disposeListener) this.disposeListener()
262
+ if (this.idleTimer) clearInterval(this.idleTimer)
263
+ for (const a of this.adapterList) { try { a.stop() } catch {} }
264
+ this.adapterList = []
265
+ this.adapters.clear()
266
+ for (const chat of this.chats.values()) chat.dispose().catch(() => {})
267
+ this.chats.clear()
268
+ this.sessionToChat.clear()
269
+ this.sessionToThread.clear()
270
+ this.threadToSession.clear()
271
+ for (const pending of this.pendingAsks.values()) {
272
+ releaseCallbacks(this.callbackIndex, pending.callbackKeys)
273
+ rejectPendingAsk(pending, new Error('gateway stopped'))
274
+ }
275
+ this.pending.clear()
276
+ this.pendingAsks.clear()
277
+ this.callbackIndex.clear()
278
+ }
279
+
280
+ getAdapter(platform) { return this.adapters.get(platform) }
281
+
282
+ async messengerSend(target, payload) {
283
+ let resolved = target
284
+ if (!resolved?.chatId && resolved?.platform) {
285
+ const home = this.resolveHomeTarget(resolved.platform, resolved.home || resolved.name)
286
+ if (!home) throw new Error('target.chatId required (or set telegram home channel)')
287
+ resolved = { ...home, ...resolved, chatId: home.chatId, threadId: resolved.threadId ?? home.threadId }
288
+ }
289
+ const adapter = this.getAdapter(resolved.platform)
290
+ if (!adapter?.sendTo) throw new Error(`adapter ${resolved.platform} unavailable`)
291
+ try {
292
+ await adapter.sendTo(resolved.chatId, payload, { threadId: resolved.threadId })
293
+ this.stats.sent++
294
+ } catch (err) {
295
+ this.stats.errors++
296
+ if (isTopicGoneError(err)) {
297
+ this.logger?.warn?.(`messengerSend: topic gone for ${resolved.platform}:${resolved.chatId}:${resolved.threadId} — the chat/topic was deleted; skipping delivery`)
298
+ return
299
+ }
300
+ throw err
301
+ }
302
+ }
303
+
304
+ async messengerAsk(target, payload, timeoutMs = 300_000) {
305
+ const adapter = this.getAdapter(target.platform)
306
+ if (!adapter) throw new Error(`adapter ${target.platform} unavailable`)
307
+ const token = makeAskToken()
308
+ const isMulti = payload.mode === 'multi' || (Array.isArray(payload.options) && payload.options.length > 0)
309
+ let replyMarkup
310
+ let callbackKeys
311
+ let selectedSet
312
+ let page = 0
313
+ const pageSize = Number(payload.pageSize) || 6
314
+
315
+ if (isMulti) {
316
+ selectedSet = new Set(Array.isArray(payload.selected) ? payload.selected : [])
317
+ const kb = buildMultiSelectKeyboard(token, payload.options || payload.buttons, selectedSet, page, pageSize, payload)
318
+ replyMarkup = kb.replyMarkup
319
+ callbackKeys = kb.callbackKeys
320
+ } else {
321
+ const kb = buildInlineKeyboard(token, payload.buttons || [])
322
+ replyMarkup = kb.replyMarkup
323
+ callbackKeys = kb.callbackKeys
324
+ }
325
+
326
+ indexCallbacks(this.callbackIndex, callbackKeys, token)
327
+ try {
328
+ await adapter.sendTo(target.chatId, { text: payload.text, replyMarkup }, { threadId: target.threadId })
329
+ } catch (err) {
330
+ // Never leave stale callback keys pointing at an unresolvable ask.
331
+ releaseCallbacks(this.callbackIndex, callbackKeys)
332
+ if (isTopicGoneError(err)) {
333
+ this.logger?.warn?.(`messengerAsk: topic gone for ${target.platform}:${target.chatId}:${target.threadId} — ask aborted (chat/topic deleted)`)
334
+ throw new Error('messenger.ask: chat or topic was deleted')
335
+ }
336
+ throw err
337
+ }
338
+ return new Promise((resolve, reject) => {
339
+ const timer = setTimeout(() => {
340
+ this.pendingAsks.delete(token)
341
+ releaseCallbacks(this.callbackIndex, callbackKeys)
342
+ reject(new Error('messenger.ask timed out'))
343
+ }, timeoutMs)
344
+ timer.unref?.()
345
+ this.pendingAsks.set(token, {
346
+ resolve, reject, timer, target, callbackKeys, isMulti,
347
+ options: payload.options || payload.buttons,
348
+ selected: selectedSet,
349
+ page, pageSize, payload,
350
+ })
351
+ })
352
+ }
353
+
354
+ async messengerProgress(target, payload) {
355
+ await this.messengerSend(target, { text: payload.text })
356
+ }
357
+
358
+ async handleUnauthorized(input) {
359
+ const { reply, userId, username } = input
360
+ const locale = this.resolveLocale(input)
361
+ if (!this.tg().pairingEnabled) {
362
+ await reply(t('msg.not_allowed', {}, locale))
363
+ return
364
+ }
365
+ try {
366
+ const { code } = this.pairing.requestCode(userId, { username })
367
+ await reply(t('msg.pairing_requested', { userId, code }, locale))
368
+ this.sendAlert('pairing', { userId, username, code }).catch(() => {})
369
+ } catch (err) {
370
+ if (err.code === 'RATE_LIMIT') await reply(t('msg.pairing_rate_limit', {}, locale))
371
+ else await reply(t('msg.exception', { message: err.message }, locale))
372
+ }
373
+ }
374
+
375
+ async handleCallback(cb) {
376
+ if (cb.userId && !this.isUserAllowed(cb.userId)) {
377
+ try { await cb.answer(t('msg.not_allowed', {}, 'en')) } catch {}
378
+ return
379
+ }
380
+ const indexed = this.callbackIndex.get(cb.data)
381
+ const { token, buttonId } = parseCallbackData(cb.data)
382
+ const askToken = indexed || token
383
+ if (askToken && this.pendingAsks.has(askToken)) {
384
+ const pending = this.pendingAsks.get(askToken)
385
+ if (!targetMatchesAsk(pending, cb)) {
386
+ await cb.answer(t('ask.other_chat', {}, 'en'))
387
+ return
388
+ }
389
+ const action = parseAskCallback(cb.data)
390
+ if (pending.isMulti) {
391
+ if (action.kind === 'toggle') {
392
+ if (pending.selected.has(action.id)) pending.selected.delete(action.id)
393
+ else pending.selected.add(action.id)
394
+ releaseCallbacks(this.callbackIndex, pending.callbackKeys)
395
+ const nextKb = buildMultiSelectKeyboard(askToken, pending.options, pending.selected, pending.page, pending.pageSize, pending.payload)
396
+ pending.callbackKeys = nextKb.callbackKeys
397
+ indexCallbacks(this.callbackIndex, nextKb.callbackKeys, askToken)
398
+ try {
399
+ if (cb.editReplyMarkup) await cb.editReplyMarkup(nextKb.replyMarkup)
400
+ else await cb.editMessage(cb.message?.text || 'Selection', nextKb.replyMarkup)
401
+ } catch {}
402
+ await cb.answer(pending.selected.has(action.id) ? 'Selected' : 'Deselected')
403
+ return
404
+ }
405
+ if (action.kind === 'page') {
406
+ pending.page = action.page
407
+ releaseCallbacks(this.callbackIndex, pending.callbackKeys)
408
+ const nextKb = buildMultiSelectKeyboard(askToken, pending.options, pending.selected, pending.page, pending.pageSize, pending.payload)
409
+ pending.callbackKeys = nextKb.callbackKeys
410
+ indexCallbacks(this.callbackIndex, nextKb.callbackKeys, askToken)
411
+ try {
412
+ if (cb.editReplyMarkup) await cb.editReplyMarkup(nextKb.replyMarkup)
413
+ else await cb.editMessage(cb.message?.text || 'Selection', nextKb.replyMarkup)
414
+ } catch {}
415
+ await cb.answer()
416
+ return
417
+ }
418
+ if (action.kind === 'done') {
419
+ this.pendingAsks.delete(askToken)
420
+ clearTimeout(pending.timer)
421
+ releaseCallbacks(this.callbackIndex, pending.callbackKeys)
422
+ await cb.answer('OK')
423
+ try { await cb.editMessage(cb.message?.text || 'Done', REMOVE_KEYBOARD) } catch {}
424
+ pending.resolve({ buttonId: 'done', selected: Array.from(pending.selected), data: cb.data })
425
+ return
426
+ }
427
+ if (action.kind === 'cancel') {
428
+ this.pendingAsks.delete(askToken)
429
+ clearTimeout(pending.timer)
430
+ releaseCallbacks(this.callbackIndex, pending.callbackKeys)
431
+ await cb.answer('Cancelled')
432
+ try { await cb.editMessage(cb.message?.text || 'Cancelled', REMOVE_KEYBOARD) } catch {}
433
+ pending.resolve({ buttonId: 'cancel', selected: [], data: cb.data })
434
+ return
435
+ }
436
+ }
437
+ this.pendingAsks.delete(askToken)
438
+ clearTimeout(pending.timer)
439
+ releaseCallbacks(this.callbackIndex, pending.callbackKeys)
440
+ await cb.answer('OK')
441
+ try { await cb.editMessage(cb.message?.text || 'Done', REMOVE_KEYBOARD) } catch {}
442
+ pending.resolve({ buttonId: action.id || buttonId, data: cb.data })
443
+ return
444
+ }
445
+
446
+ // Model picker interactive flow
447
+ if (cb.data?.startsWith('mdl:')) {
448
+ const parts = cb.data.split(':')
449
+ const sub = parts[1]
450
+ // Step 2: Selected provider -> show its models (10 per page)
451
+ if (sub === 'p') {
452
+ const providerId = parts.slice(2).join(':')
453
+ const current = this.resolveAgentModel()
454
+ const catalog = await listModelCatalog(this.ctx, current)
455
+ const models = catalog.modelsByProvider.get(providerId) || []
456
+ if (!models.length) {
457
+ await cb.answer(t('model.no_models', {}, 'en'))
458
+ return
459
+ }
460
+ const kb = buildModelsKeyboard(providerId, models, current.model, 0)
461
+ await cb.answer()
462
+ const text = [
463
+ `🤖 <b>Provider:</b> <code>${providerId}</code>`,
464
+ `Select model (page ${kb.page + 1}/${kb.totalPages}):`,
465
+ ].join('\n')
466
+ try {
467
+ if (cb.editMessage) await cb.editMessage(text, kb)
468
+ } catch {}
469
+ return
470
+ }
471
+ // Pagination for models
472
+ if (sub === 'pg') {
473
+ const page = parseInt(parts[parts.length - 1], 10) || 0
474
+ const providerId = parts.slice(2, -1).join(':')
475
+ const current = this.resolveAgentModel()
476
+ const catalog = await listModelCatalog(this.ctx, current)
477
+ const models = catalog.modelsByProvider.get(providerId) || []
478
+ const kb = buildModelsKeyboard(providerId, models, current.model, page)
479
+ await cb.answer()
480
+ const text = [
481
+ `🤖 <b>Provider:</b> <code>${providerId}</code>`,
482
+ `Select model (page ${kb.page + 1}/${kb.totalPages}):`,
483
+ ].join('\n')
484
+ try {
485
+ if (cb.editMessage) await cb.editMessage(text, kb)
486
+ } catch {}
487
+ return
488
+ }
489
+ // Back to providers
490
+ if (sub === 'back') {
491
+ const current = this.resolveAgentModel()
492
+ const catalog = await listModelCatalog(this.ctx, current)
493
+ const kb = buildProvidersKeyboard(catalog.providers, current)
494
+ await cb.answer()
495
+ const text = [
496
+ '🤖 <b>Choose Provider:</b>',
497
+ `Current: <code>${current.provider}/${current.model}</code>`,
498
+ ].join('\n')
499
+ try {
500
+ if (cb.editMessage) await cb.editMessage(text, kb)
501
+ } catch {}
502
+ return
503
+ }
504
+ // Select model
505
+ if (sub === 's') {
506
+ const key = parts[2]
507
+ const stored = getStoredModelSelection(key)
508
+ if (!stored) {
509
+ await cb.answer(t('ask.expired', {}, 'en'))
510
+ return
511
+ }
512
+ const { provider, model } = stored
513
+ try {
514
+ const adm = this.ctx.get('agentDefaultModel')
515
+ if (adm?.saveSelection) {
516
+ await adm.saveSelection({ provider, model })
517
+ }
518
+ this.config.agent = { ...this.config.agent, provider, model }
519
+ try {
520
+ await this.hooks?.persistAgentModel?.({ provider, model })
521
+ } catch (e) {
522
+ this.ctx.logger?.warn?.(`persist agent model: ${e.message}`)
523
+ }
524
+ await cb.answer(t('ask.chose', { choice: model }, 'en'))
525
+ try {
526
+ if (cb.editMessage) await cb.editMessage(t('model.switched', { provider, model }, 'en'), REMOVE_KEYBOARD)
527
+ } catch {}
528
+ } catch (err) {
529
+ await cb.answer(`Error: ${err.message}`)
530
+ }
531
+ return
532
+ }
533
+ if (sub === 'cur') {
534
+ await cb.answer()
535
+ return
536
+ }
537
+ }
538
+
539
+ await cb.answer()
540
+ }
541
+
542
+ sessionKeyFor(input) {
543
+ const scope = this.config.agent?.sessionScope || 'user'
544
+ return sessionKey({
545
+ platform: input.platform,
546
+ chatId: input.chatId,
547
+ threadId: input.threadId || 0,
548
+ userId: input.userId,
549
+ chatType: input.chatType,
550
+ scope,
551
+ })
552
+ }
553
+
554
+ isChatBusy(chat) {
555
+ return Boolean(chat?.turnActive)
556
+ }
557
+
558
+ async handleMessage(input) {
559
+ const { platform, chatId, threadId = 0, text, reply } = input
560
+ const key = this.sessionKeyFor(input)
561
+ const body = String(text || '').trim()
562
+ let attachments = [...(input.attachments || [])]
563
+ const hasMedia = attachments.length > 0
564
+ if (!body && !hasMedia) return
565
+ if (body.startsWith('/')) { await this.handleCommand(key, body, input); return }
566
+ try {
567
+ const chat = await this.getOrCreateChat(key, input)
568
+ const photoOnlyMode = this.config.agent?.photoOnlyMode ?? 'prompt'
569
+ const incomingPhotoOnly = hasMedia && attachments.every((a) => a.kind === 'photo' || a.kind === 'sticker') && !body
570
+ if (incomingPhotoOnly && photoOnlyMode === 'prompt') {
571
+ chat.pendingMedia = [...(chat.pendingMedia || []), ...attachments]
572
+ const n = chat.pendingMedia.length
573
+ const locale = this.resolveLocale(input)
574
+ const msg = n === 1
575
+ ? t('photo.received_one', {}, locale)
576
+ : t('photo.received_many', { count: n }, locale)
577
+ return reply(msg)
578
+ }
579
+ if (chat.pendingMedia?.length) {
580
+ attachments = [...chat.pendingMedia, ...attachments]
581
+ chat.pendingMedia = []
582
+ }
583
+ const inboundWasVoice = attachments.some((a) => a.kind === 'voice' || a.kind === 'audio')
584
+ let personaOverride
585
+ for (const [pId] of Object.entries(BUILTIN_PERSONAS)) {
586
+ if (pId === 'default') continue
587
+ const tag = `@${pId}`
588
+ if (body.toLowerCase().includes(tag)) {
589
+ personaOverride = pId
590
+ break
591
+ }
592
+ }
593
+ const turnInput = { ...input, text: body, attachments, inboundWasVoice, personaOverride }
594
+
595
+ // Hermes-like steer: while a turn is running, inject followup instead of abort+restart
596
+ if (this.isChatBusy(chat)) {
597
+ const steerText = body || (hasMedia ? '(steer: media)' : '')
598
+ const content = await this.buildUserContent({
599
+ ...turnInput,
600
+ text: steerText,
601
+ steer: true,
602
+ }, undefined)
603
+ chat.agent.followup(createUserMessage({
604
+ content: ensureContentArray(content),
605
+ source: { kind: 'user', plugin: PLUGIN, form: 'steer', origin: 'telegram' },
606
+ }))
607
+ chat.lastUsed = Date.now()
608
+ try { await reply(t('msg.steer_added', {}, this.resolveLocale(input))) } catch {}
609
+ return
610
+ }
611
+
612
+ // Mark busy BEFORE yielding to the poll loop, otherwise steer/stop never see an active turn.
613
+ chat.turnActive = true
614
+ try { chat.abort?.abort?.() } catch {}
615
+ chat.abort = new AbortController()
616
+ const run = chat.busy.then(() => this.runTurn(chat, turnInput, chat.abort.signal))
617
+ chat.busy = run.catch(() => {})
618
+ // Do NOT await: Telegram poll is sequential; awaiting blocked steer and /stop until the turn finished.
619
+ run.catch((err) => {
620
+ const msg = err instanceof Error ? err.message : String(err)
621
+ this.ctx.logger?.warn?.(`dsh-messenger-gateway: background turn: ${msg}`)
622
+ this.sendAlert('error', {
623
+ code: err?.code || 'BACKGROUND_ERROR',
624
+ message: msg,
625
+ sessionId: chat.agent?.session?.id,
626
+ chatId: input.chatId,
627
+ threadId: input.threadId,
628
+ }).catch(() => {})
629
+ chat.turnActive = false
630
+ chat.abort = undefined
631
+ })
632
+ } catch (err) {
633
+ const msg = err instanceof Error ? err.message : String(err)
634
+ this.ctx.logger?.warn?.(`dsh-messenger-gateway: message: ${msg}`)
635
+ try { await reply(t('msg.exception', { message: msg }, this.resolveLocale(input))) } catch {}
636
+ }
637
+ }
638
+
639
+ async handleCommand(key, text, input) {
640
+ const parts = text.split(/\s+/)
641
+ const cmd = parts[0].toLowerCase().split('@')[0]
642
+ const { reply, userId, chatId, threadId = 0, platform } = input
643
+ const locale = this.resolveLocale(input)
644
+
645
+ if (cmd === '/start') {
646
+ return reply(t('msg.start', {}, locale), { replyMarkup: REMOVE_REPLY_KEYBOARD })
647
+ }
648
+
649
+ if (cmd === '/help') {
650
+ return reply([
651
+ '📖 <b>Messenger Gateway Help:</b>',
652
+ '',
653
+ '💬 <b>Session & Chat:</b>',
654
+ ' /help show this command reference',
655
+ '• /new — start fresh session',
656
+ '• /stop interrupt current response',
657
+ '• /model — interactive model selector (/model list)',
658
+ '• /role [name] — switch persona or role (/role list)',
659
+ '• /bind [role] — bind persona to topic / chat',
660
+ '• /preset [name] — bind preset to topic / chat',
661
+ '• /lang [en|zh] — switch user language',
662
+ '• /rewind [N] rewind last N turns',
663
+ '• /fork fork session into new branch',
664
+ '• /export export history to Markdown',
665
+ '',
666
+ '🛠️ <b>Tools, Files & Cron:</b>',
667
+ '• /skills / /tools — list active tools & skills',
668
+ '• /files [dir] — workspace file explorer',
669
+ '• /get <path> — download file from workspace',
670
+ '• /remind <time> <text> — set reminder (/remind 10m check deploy)',
671
+ '• /cron <interval> <prompt> — recurring autonomous task',
672
+ '',
673
+ '⚙️ <b>Settings & Stats:</b>',
674
+ '• /status — gateway and active model status',
675
+ ' /top system resource usage (RAM, uptime)',
676
+ '• /keyboard on|off — quick action keyboard',
677
+ '• /voice on|off|status voice replies preference',
678
+ '• /tts on|off|status speech synthesis in this chat',
679
+ '• /mute / /unmute mute notifications in this chat',
680
+ '',
681
+ '🔒 <b>Access & Channels:</b>',
682
+ '• /whoami your messenger user ID',
683
+ '• /pair CODE — approve pairing code',
684
+ ' /sethome [name] set home notification channel',
685
+ '• /setalert — set alert channel',
686
+ ].join('\n'))
687
+ }
688
+
689
+ if (cmd === '/lang' || cmd === '/language') {
690
+ const sub = parts[1]?.toLowerCase()
691
+ if (sub === 'en' || sub === 'zh') {
692
+ this.chatLocales.set(chatId, sub)
693
+ return reply(sub === 'zh' ? '语言已切换为中文 (zh)' : 'Language switched to English (en)')
694
+ }
695
+ const cur = this.chatLocales.get(chatId) || this.config?.defaultLocale || 'en'
696
+ return reply(`Current language: <b>${cur}</b>\nSwitch: <code>/lang en</code> or <code>/lang zh</code>`)
697
+ }
698
+
699
+ if (cmd === '/bind') {
700
+ const targetRole = parts[1]?.toLowerCase()
701
+ if (!targetRole || targetRole === 'list') {
702
+ const cur = this.personas.getPersonaForChat(chatId, threadId)
703
+ return reply(`${t('persona.title', {}, locale)}\nCurrent bound role: <b>${cur}</b>\nUsage: <code>/bind &lt;role&gt;</code> (or /bind reset)`)
704
+ }
705
+ if (targetRole === 'reset' || targetRole === 'default') {
706
+ this.personas.set(chatId, 'default', threadId)
707
+ return reply(t('persona.reset', {}, locale))
708
+ }
709
+ const persona = getPersona(targetRole)
710
+ if (!persona) return reply(t('persona.unknown', { target: targetRole }, locale))
711
+ this.personas.set(chatId, targetRole, threadId)
712
+ return reply(t('persona.bound_topic', { kind: 'role', name: `${persona.icon} ${persona.name}` }, locale))
713
+ }
714
+
715
+ if (cmd === '/preset') {
716
+ const presetName = parts[1]
717
+ if (!presetName || presetName === 'list') {
718
+ const cur = this.personas.getPreset(chatId, threadId) || '(none)'
719
+ return reply(`🎭 <b>Presets:</b>\nCurrent topic preset: <code>${cur}</code>\nUsage: <code>/preset &lt;name&gt;</code> or <code>/preset reset</code>`)
720
+ }
721
+ if (presetName === 'reset' || presetName === 'clear') {
722
+ this.personas.setPreset(chatId, threadId, null)
723
+ return reply('Preset cleared for this topic.')
724
+ }
725
+ this.personas.setPreset(chatId, threadId, presetName)
726
+ return reply(t('persona.bound_topic', { kind: 'preset', name: presetName }, locale))
727
+ }
728
+
729
+ if (cmd === '/cron') {
730
+ const sub = parts[1]?.toLowerCase()
731
+ if (sub === 'list') {
732
+ const list = await this.scheduler.listRecurring(chatId)
733
+ if (!list.length) return reply(t('cron.none', {}, locale))
734
+ const lines = [t('cron.list_title', {}, locale)]
735
+ for (const task of list) {
736
+ const left = formatRemaining(task.dueAt - Date.now(), locale)
737
+ lines.push(`• <code>${task.id}</code> (every ${formatRemaining(task.intervalMs, locale)}, next in ${left}): ${task.prompt || task.text}`)
738
+ }
739
+ lines.push('\nCancel: <code>/cron cancel ID</code>')
740
+ return reply(lines.join('\n'))
741
+ }
742
+ if (sub === 'cancel') {
743
+ const targetId = parts[2]
744
+ if (!targetId) return reply('Specify cron task ID: <code>/cron cancel ID</code>')
745
+ const ok = await this.scheduler.cancel(targetId, chatId)
746
+ return reply(ok ? t('cron.cancelled', { id: targetId }, locale) : `Task not found: <code>${targetId}</code>`)
747
+ }
748
+ const specArg = parts[1]
749
+ const promptArg = parts.slice(2).join(' ')
750
+ const ms = parseRelativeTime(specArg)
751
+ if (!ms || !promptArg) {
752
+ return reply('⏱️ <b>Autonomous Cron Tasks:</b>\nCreate: <code>/cron &lt;interval&gt; &lt;prompt&gt;</code>\nExample: <code>/cron 1h check server logs</code>\nList: <code>/cron list</code>\nCancel: <code>/cron cancel ID</code>')
753
+ }
754
+ const task = await this.scheduler.schedule({
755
+ platform,
756
+ chatId,
757
+ threadId,
758
+ userId,
759
+ text: promptArg,
760
+ prompt: promptArg,
761
+ dueAt: Date.now() + ms,
762
+ recurring: true,
763
+ intervalMs: ms,
764
+ })
765
+ return reply(t('cron.scheduled', { id: task.id, schedule: specArg, prompt: promptArg }, locale))
766
+ }
767
+
768
+ if (cmd === '/role' || cmd === '/persona') {
769
+ const targetRole = parts[1]?.toLowerCase()
770
+ if (!targetRole || targetRole === 'list') {
771
+ const currentId = this.personas.getPersonaForChat(chatId, threadId)
772
+ const lines = [
773
+ t('persona.title', {}, locale),
774
+ '',
775
+ ...listPersonas().map((p) => {
776
+ const isCurrent = p.id === currentId ? ' (active)' : ''
777
+ return `${p.icon} <b>${p.id}</b> — ${p.name}: ${p.description}${isCurrent}`
778
+ }),
779
+ '',
780
+ t('persona.usage', {}, locale),
781
+ ]
782
+ return reply(lines.join('\n'))
783
+ }
784
+ if (targetRole === 'reset' || targetRole === 'default') {
785
+ this.personas.set(chatId, 'default', threadId)
786
+ return reply(t('persona.reset', {}, locale))
787
+ }
788
+ const persona = getPersona(targetRole)
789
+ if (!persona) {
790
+ return reply(t('persona.unknown', { target: targetRole }, locale))
791
+ }
792
+ this.personas.set(chatId, persona.id, threadId)
793
+ return reply(t('persona.switched', { icon: persona.icon, name: persona.name, description: persona.description }, locale))
794
+ }
795
+
796
+ if (cmd === '/skills' || cmd === '/tools') {
797
+ const tools = this.ctx.get?.('tools') || this.ctx.tools
798
+ const toolsList = []
799
+ if (tools?.tools) {
800
+ for (const [name, tDef] of tools.tools.entries()) {
801
+ toolsList.push(`• <b>${name}</b>: ${tDef.description || '(no description)'}`)
802
+ }
803
+ }
804
+ if (!toolsList.length) {
805
+ return reply('🛠️ <b>Agent Tools:</b>\n(no tools registered)')
806
+ }
807
+ return reply([
808
+ '🛠️ <b>Active Tools & Skills:</b>',
809
+ '',
810
+ ...toolsList,
811
+ ].join('\n'))
812
+ }
813
+
814
+ if (cmd === '/export') {
815
+ const chat = this.chats.get(key)
816
+ if (!chat?.agent?.session) {
817
+ return reply(t('msg.no_active_session', {}, locale))
818
+ }
819
+ try {
820
+ const { filename, buffer, messagesCount } = exportSessionToMarkdown(chat.agent.session)
821
+ if (!messagesCount) {
822
+ return reply(t('export.empty', {}, locale))
823
+ }
824
+ const file = {
825
+ name: filename,
826
+ mime: 'text/markdown',
827
+ kind: 'document',
828
+ bytes: buffer,
829
+ }
830
+ return reply({ text: t('export.title', { count: messagesCount }, locale), files: [file] })
831
+ } catch (err) {
832
+ return reply(`Export error: ${err.message}`)
833
+ }
834
+ }
835
+
836
+ if (cmd === '/rewind') {
837
+ const chat = this.chats.get(key)
838
+ if (!chat?.agent?.session) {
839
+ return reply(t('msg.no_active_session', {}, locale))
840
+ }
841
+ const count = Number(parts[1]) || 1
842
+ const res = rewindSession(chat.agent.session, count)
843
+ if (!res.removed) {
844
+ return reply('No turns to rewind in session history.')
845
+ }
846
+ const sessions = this.ctx.get?.('sessions') || this.ctx.sessions
847
+ try { await sessions?.flush(chat.agent.session) } catch {}
848
+ return reply(`⏪ Rewound ${res.removed} messages. Remaining in context: ${res.remaining}.`)
849
+ }
850
+
851
+ if (cmd === '/fork') {
852
+ const chat = this.chats.get(key)
853
+ if (!chat?.agent?.session) {
854
+ return reply(t('msg.no_active_session', {}, locale))
855
+ }
856
+ try {
857
+ const oldSession = chat.agent.session
858
+ const oldMessages = Array.isArray(oldSession.messages)
859
+ ? oldSession.messages.map(m => ({ ...m, content: ensureContentArray(m.content) }))
860
+ : []
861
+ const newChat = await this.createChat(key, input)
862
+ if (newChat.agent?.session && oldMessages.length) {
863
+ newChat.agent.session.messages = oldMessages
864
+ const sessions = this.ctx.get?.('sessions') || this.ctx.sessions
865
+ try { await sessions?.flush(newChat.agent.session) } catch {}
866
+ }
867
+ this.chats.set(key, newChat)
868
+ return reply(`🔀 Forked session!\nOld session: ${oldSession.id}\nNew session: ${newChat.agent.session.id}\nContext preserved (${oldMessages.length} messages).`)
869
+ } catch (err) {
870
+ return reply(`Fork error: ${err.message}`)
871
+ }
872
+ }
873
+
874
+ if (cmd === '/files') {
875
+ const subPath = parts.slice(1).join(' ').trim() || '.'
876
+ const agentCwd = this.config.agent?.cwd || process.cwd()
877
+ const res = await listFiles(agentCwd, subPath)
878
+ if (!res.ok) return reply(`❌ ${res.error}`)
879
+ return reply(res.formattedText)
880
+ }
881
+
882
+ if (cmd === '/get') {
883
+ const targetRel = parts.slice(1).join(' ').trim()
884
+ if (!targetRel) {
885
+ return reply('Specify file path to download: <code>/get &lt;path&gt;</code>\nBrowse: <code>/files</code>')
886
+ }
887
+ const agentCwd = this.config.agent?.cwd || process.cwd()
888
+ const maxDocBytes = Number(this.config.media?.maxDocBytes) || 50 * 1024 * 1024
889
+ const res = await getFileForDownload(agentCwd, targetRel, maxDocBytes)
890
+ if (!res.ok) return reply(`❌ ${res.error}`)
891
+ const file = {
892
+ name: res.name,
893
+ mime: res.mime,
894
+ kind: 'document',
895
+ bytes: res.bytes,
896
+ dataBase64: res.bytes.toString('base64'),
897
+ }
898
+ return reply({ text: `📄 File: <b>${res.name}</b> (${formatFileSize(res.size)})`, files: [file] })
899
+ }
900
+
901
+ if (cmd === '/new') {
902
+ const chat = this.chats.get(key)
903
+ if (chat) {
904
+ if (chat.abort) chat.abort.abort()
905
+ chat.pendingMedia = []
906
+ this.sessionToChat.delete(String(chat.agent.session.id))
907
+ this.chats.delete(key)
908
+ await chat.dispose()
909
+ return reply('Session reset.')
910
+ }
911
+ return reply(t('msg.no_active_session', {}, locale))
912
+ }
913
+
914
+ if (cmd === '/whoami') {
915
+ const lines = [`User ID: ${userId}`]
916
+ if (chatId) lines.push(`chatId: ${chatId}`)
917
+ if (threadId) lines.push(`threadId: ${threadId}`)
918
+ return reply(lines.join('\n'))
919
+ }
920
+
921
+ if (cmd === '/stop') {
922
+ const chat = this.chats.get(key)
923
+ if (chat?.turnActive || chat?.abort) {
924
+ try { chat.abort?.abort() } catch {}
925
+ releaseChatTurn(chat)
926
+ chat.turnActive = false
927
+ return reply(t('msg.turn_stopped', {}, locale))
928
+ }
929
+ return reply('Nothing to stop.')
930
+ }
931
+
932
+ if (cmd === '/status') {
933
+ let modelLine = 'model: (not set)'
934
+ try {
935
+ const sel = this.resolveAgentModel()
936
+ modelLine = `model: ${sel.provider}/${sel.model}`
937
+ } catch (e) {
938
+ modelLine = `model: ${e.message}`
939
+ }
940
+ const home = this.resolveHomeTarget(platform || 'telegram')
941
+ const homeLine = home
942
+ ? `home: chat ${home.chatId}${home.threadId ? ` topic ${home.threadId}` : ''}`
943
+ : 'home: (not set)'
944
+ const pending = this.pairing.listPending().length
945
+ const up = Math.max(0, Math.round((Date.now() - this.stats.startedAt) / 1000))
946
+ const hh = String(Math.floor(up / 3600)).padStart(2, '0')
947
+ const mm = String(Math.floor((up % 3600) / 60)).padStart(2, '0')
948
+ const ss = String(up % 60).padStart(2, '0')
949
+ return reply([
950
+ 'Messenger gateway',
951
+ `adapters: ${[...this.adapters.keys()].join(', ') || '(none)'}`,
952
+ `active chats: ${this.chats.size}`,
953
+ modelLine,
954
+ homeLine,
955
+ `pairing pending: ${pending}`,
956
+ `transport: ${this.tg().transport || 'poll'}`,
957
+ `sessionScope: ${this.config.agent?.sessionScope || 'user'}`,
958
+ `delivered: ${this.stats.sent}`,
959
+ `errors: ${this.stats.errors}`,
960
+ `polling conflict: ${this.tgAdapter?.pollingConflict ? 'yes' : 'no'}`,
961
+ `uptime: ${hh}:${mm}:${ss}`,
962
+ ].join('\n'))
963
+ }
964
+
965
+ if (cmd === '/model') {
966
+ if (parts.length >= 3) {
967
+ if (!this.isUserAllowed(userId)) return reply(t('msg.not_allowed', {}, locale))
968
+ const provider = parts[1]
969
+ const model = parts.slice(2).join(' ')
970
+ try {
971
+ const adm = this.ctx.get('agentDefaultModel')
972
+ if (adm?.saveSelection) {
973
+ await adm.saveSelection({ provider, model })
974
+ }
975
+ this.config.agent = { ...this.config.agent, provider, model }
976
+ try {
977
+ await this.hooks?.persistAgentModel?.({ provider, model })
978
+ } catch (e) {
979
+ this.ctx.logger?.warn?.(`persist agent model: ${e.message}`)
980
+ }
981
+ return reply(t('model.switched', { provider, model }, locale))
982
+ } catch (e) {
983
+ return reply(`Failed to switch model: ${e.message}`)
984
+ }
985
+ }
986
+ try {
987
+ const current = this.resolveAgentModel()
988
+ const catalog = await listModelCatalog(this.ctx, current)
989
+ if (!catalog.providers.length) {
990
+ return reply(`Current model: <code>${current.provider}/${current.model}</code>\nSwitch: <code>/model &lt;provider&gt; &lt;model&gt;</code>`)
991
+ }
992
+ const kb = buildProvidersKeyboard(catalog.providers, current)
993
+ return reply([
994
+ t('model.title', {}, locale),
995
+ t('model.current', { current: `${current.provider}/${current.model}` }, locale),
996
+ ].join('\n'), {
997
+ replyMarkup: kb,
998
+ })
999
+ } catch (e) {
1000
+ return reply(e.message)
1001
+ }
1002
+ }
1003
+
1004
+ if (cmd === '/pair') {
1005
+ if (!this.isUserAllowed(userId)) return reply('Only users in allowlist can approve /pair.')
1006
+ const code = parts[1]
1007
+ if (!code) return reply('Usage: /pair CODE')
1008
+ const res = this.pairing.approveCode(code, userId)
1009
+ if (!res.ok) return reply(`Failed: ${res.error}`)
1010
+ const merged = this.effectiveAllowedIds()
1011
+ for (const a of this.adapterList) a.setAllowedUserIds?.(merged)
1012
+ try { await this.hooks?.persistAllowedUserIds?.(merged) } catch (e) {
1013
+ this.ctx.logger?.warn?.(`persist allowlist: ${e.message}`)
1014
+ }
1015
+ return reply(`Approved user ID ${res.userId}${res.username ? ` (@${res.username})` : ''}.`)
1016
+ }
1017
+
1018
+ if (cmd === '/sethome') {
1019
+ if (!this.isUserAllowed(userId)) return reply(t('msg.not_allowed', {}, locale))
1020
+ const name = normalizeHomeName(parts[1] || 'default') || 'default'
1021
+ try {
1022
+ const nextTg = upsertHome(this.tg(), { name, chatId, threadId })
1023
+ await this.hooks?.persistHomes?.(nextTg)
1024
+ this.config.telegram = nextTg
1025
+ return reply(`Home "${name}": chat ${chatId}${threadId ? ` topic ${threadId}` : ''}`)
1026
+ } catch (e) {
1027
+ return reply(`Failed to save home: ${e.message}`)
1028
+ }
1029
+ }
1030
+
1031
+ if (cmd === '/home') {
1032
+ const homes = listHomes(this.tg())
1033
+ if (!homes.length) return reply('Home is not set. /sethome or /sethome <name>')
1034
+ return reply(['Homes:', ...homes.map((h) => `• ${h.name}: chat ${h.chatId}${h.threadId ? ` topic ${h.threadId}` : ''}`)].join('\n'))
1035
+ }
1036
+
1037
+ if (cmd === '/setalert') {
1038
+ if (!this.isUserAllowed(userId)) return reply(t('msg.not_allowed', {}, locale))
1039
+ const nextTg = {
1040
+ ...this.tg(),
1041
+ alerts: {
1042
+ ...(this.tg().alerts || {}),
1043
+ enabled: true,
1044
+ chatId,
1045
+ threadId: threadId || 0,
1046
+ },
1047
+ }
1048
+ this.config.telegram = nextTg
1049
+ try { await this.hooks?.persistHomes?.(nextTg) } catch {}
1050
+ return reply(`🔔 This chat assigned as alert channel (chat: ${chatId}${threadId ? `, topic: ${threadId}` : ''}).`)
1051
+ }
1052
+
1053
+ if (cmd === '/alert') {
1054
+ const sub = parts[1]?.toLowerCase()
1055
+ if (sub === 'test') {
1056
+ const target = resolveAlertTarget(this)
1057
+ if (!target) return reply('Alert channel not configured. Configure: /setalert')
1058
+ await this.sendAlert('status', { title: 'Test Alert', details: `Sent by user ID ${userId}` })
1059
+ return reply('Test alert sent to alert channel.')
1060
+ }
1061
+ const target = resolveAlertTarget(this)
1062
+ const alertsCfg = this.tg().alerts || {}
1063
+ return reply([
1064
+ '🔔 <b>Alert Channel:</b>',
1065
+ `Status: ${alertsCfg.enabled ? 'enabled' : 'disabled'}`,
1066
+ `Chat: ${target ? `${target.chatId}${target.threadId ? ` (topic: ${target.threadId})` : ''}` : '(not assigned)'}`,
1067
+ `Events: ${(alertsCfg.events || ['error', 'pairing']).join(', ')}`,
1068
+ '',
1069
+ 'Commands:',
1070
+ '/setalert assign current chat as alert channel',
1071
+ '/alert test send test alert',
1072
+ ].join('\n'))
1073
+ }
1074
+
1075
+ if (cmd === '/remind') {
1076
+ const sub = parts[1]?.toLowerCase()
1077
+ if (sub === 'list') {
1078
+ const active = await this.scheduler.list(chatId)
1079
+ if (!active.length) return reply('No active reminders for this chat.')
1080
+ const lines = [
1081
+ '⏰ <b>Active Reminders:</b>',
1082
+ '',
1083
+ ...active.map((tItem) => {
1084
+ const left = formatRemaining(tItem.dueAt - Date.now(), locale)
1085
+ return `• <code>${tItem.id}</code> (in ${left}): ${tItem.text}`
1086
+ }),
1087
+ '',
1088
+ 'Cancel: <code>/remind cancel ID</code>',
1089
+ ]
1090
+ return reply(lines.join('\n'))
1091
+ }
1092
+ if (sub === 'cancel') {
1093
+ const targetId = parts[2]?.trim()
1094
+ if (!targetId) return reply('Specify reminder ID: <code>/remind cancel ID</code>')
1095
+ const ok = await this.scheduler.cancel(targetId, chatId)
1096
+ return reply(ok ? `✅ Reminder <code>${targetId}</code> cancelled.` : `❌ Reminder <code>${targetId}</code> not found.`)
1097
+ }
1098
+ const timeArg = parts[1]
1099
+ const textArg = parts.slice(2).join(' ').trim()
1100
+ const delayMs = parseRelativeTime(timeArg)
1101
+ if (!delayMs || !textArg) {
1102
+ return reply([
1103
+ '⏰ <b>Reminders:</b>',
1104
+ 'Create: <code>/remind &lt;time&gt; &lt;text&gt;</code>',
1105
+ 'Examples: <code>/remind 10m Call colleague</code>, <code>/remind 2h Check deploy</code>',
1106
+ 'List: <code>/remind list</code>',
1107
+ 'Cancel: <code>/remind cancel ID</code>',
1108
+ ].join('\n'))
1109
+ }
1110
+ const dueAt = Date.now() + delayMs
1111
+ const task = await this.scheduler.schedule({
1112
+ platform: platform || 'telegram',
1113
+ chatId,
1114
+ threadId: threadId || 0,
1115
+ userId,
1116
+ text: textArg,
1117
+ dueAt,
1118
+ })
1119
+ const left = formatRemaining(delayMs, locale)
1120
+ return reply(t('remind.scheduled', { time: new Date(dueAt).toLocaleTimeString(), duration: left, text: textArg }, locale))
1121
+ }
1122
+
1123
+ if (cmd === '/voice') {
1124
+ const sub = String(parts[1] || 'status').toLowerCase()
1125
+ if (sub === 'summary') {
1126
+ const val = parts[2]?.toLowerCase()
1127
+ if (val === 'on' || val === 'off') {
1128
+ if (!this.config.tts) this.config.tts = {}
1129
+ this.config.tts.voiceSummary = val === 'on'
1130
+ return reply(`Voice summary (TL;DR): ${val === 'on' ? 'enabled' : 'disabled'}`)
1131
+ }
1132
+ const state = this.config.tts?.voiceSummary ? 'on' : 'off'
1133
+ return reply(`Voice summary (TL;DR): ${state}\nToggle: <code>/voice summary on|off</code>`)
1134
+ }
1135
+ if (sub === 'on' || sub === 'off') {
1136
+ this.voicePrefs.set(userId, sub === 'on')
1137
+ return reply(sub === 'on' ? 'Voice replies: on (for you)' : 'Voice replies: off (for you)')
1138
+ }
1139
+ const pref = this.voicePrefs.get(userId)
1140
+ const mode = this.tg().voiceMode || 'mirror'
1141
+ const prefLine = pref === null ? 'not set (/voice on|off)' : (pref ? 'on' : 'off')
1142
+ const summaryState = this.config.tts?.voiceSummary ? 'on' : 'off'
1143
+ return reply(`voiceMode=${mode}\nyour /voice: ${prefLine}\nglobal tts: ${this.config.tts?.enabled ? 'on' : 'off'}\nvoice summary: ${summaryState}`)
1144
+ }
1145
+
1146
+ if (cmd === '/topic') {
1147
+ const topicName = parts.slice(1).join(' ').trim()
1148
+ if (!topicName) {
1149
+ return reply('Usage: <code>/topic &lt;name&gt;</code>\nCreates a new topic in supergroup with an isolated session.')
1150
+ }
1151
+ const tgAdapter = this.getAdapter('telegram')
1152
+ if (!tgAdapter?.createForumTopic) {
1153
+ return reply('Topic creation is available only in Telegram.')
1154
+ }
1155
+ try {
1156
+ const res = await tgAdapter.createForumTopic(chatId, topicName)
1157
+ const newThreadId = res?.message_thread_id
1158
+ await reply(`🎯 Created new topic <b>«${topicName}»</b> (ID: <code>${newThreadId}</code>).\nSwitch to the topic to continue working!`)
1159
+ if (newThreadId) {
1160
+ await tgAdapter.sendTo(chatId, {
1161
+ text: `👋 Hello! This is an isolated session for task <b>«${topicName}»</b>.\nHow can I help?`,
1162
+ }, { threadId: newThreadId })
1163
+ }
1164
+ return
1165
+ } catch (err) {
1166
+ return reply(`Failed to create topic: ${err.message}\n(Ensure the bot is group administrator with Manage Topics permission)`)
1167
+ }
1168
+ }
1169
+
1170
+ if (cmd === '/top') {
1171
+ const mem = process.memoryUsage()
1172
+ const rssMb = (mem.rss / 1024 / 1024).toFixed(1)
1173
+ const heapMb = (mem.heapUsed / 1024 / 1024).toFixed(1)
1174
+ const sec = Math.floor((Date.now() - this.stats.startedAt) / 1000)
1175
+ const hh = String(Math.floor(sec / 3600)).padStart(2, '0')
1176
+ const mm = String(Math.floor((sec % 3600) / 60)).padStart(2, '0')
1177
+ const ss = String(sec % 60).padStart(2, '0')
1178
+ let activeReminders = 0
1179
+ try { activeReminders = (await this.scheduler.list()).length } catch {}
1180
+ let currentModel = 'not set'
1181
+ try {
1182
+ const m = this.resolveAgentModel()
1183
+ currentModel = `${m.provider}/${m.model}`
1184
+ } catch {}
1185
+
1186
+ return reply([
1187
+ '📊 <b>DSH System & Resources:</b>',
1188
+ `• <b>Memory (RSS):</b> ${rssMb} MB`,
1189
+ `• <b>Heap:</b> ${heapMb} MB`,
1190
+ `• <b>Uptime:</b> ${hh}:${mm}:${ss}`,
1191
+ `• <b>Active chats:</b> ${this.chats.size}`,
1192
+ `• <b>Queued reminders:</b> ${activeReminders}`,
1193
+ `• <b>Active model:</b> <code>${currentModel}</code>`,
1194
+ `• <b>Messages sent:</b> ${this.stats.sent}`,
1195
+ `• <b>Errors:</b> ${this.stats.errors}`,
1196
+ ].join('\n'))
1197
+ }
1198
+
1199
+ if (cmd === '/keyboard') {
1200
+ const sub = String(parts[1] || '').toLowerCase()
1201
+ const tgAdapter = this.getAdapter('telegram')
1202
+ if (sub === 'on') {
1203
+ if (tgAdapter) tgAdapter.quickActions = true
1204
+ return reply('Quick action keyboard enabled.', {
1205
+ replyMarkup: buildQuickActionsKeyboard(),
1206
+ })
1207
+ }
1208
+ if (sub === 'off') {
1209
+ if (tgAdapter) tgAdapter.quickActions = false
1210
+ return reply('Quick action keyboard disabled.', {
1211
+ replyMarkup: REMOVE_REPLY_KEYBOARD,
1212
+ })
1213
+ }
1214
+ const curState = tgAdapter?.quickActions ? 'enabled' : 'disabled'
1215
+ return reply([
1216
+ '⌨️ <b>Quick Action Keyboard:</b>',
1217
+ `Current state: <b>${curState}</b>`,
1218
+ '',
1219
+ 'Commands:',
1220
+ '<code>/keyboard on</code> show buttons',
1221
+ '<code>/keyboard off</code> hide buttons',
1222
+ ].join('\n'))
1223
+ }
1224
+
1225
+ if (cmd === '/tts') {
1226
+ const sub = String(parts[1] || 'status').toLowerCase()
1227
+ if (sub === 'on' || sub === 'off') {
1228
+ this.chatTts.set(chatId, sub === 'on')
1229
+ return reply(sub === 'on' ? 'Speech in this chat: on' : 'Speech in this chat: off')
1230
+ }
1231
+ const cur = this.chatTts.get(chatId)
1232
+ const line = cur === null ? 'not set (/tts on|off)' : (cur ? 'on' : 'off')
1233
+ return reply(`Speech in this chat: ${line}\nglobal tts: ${this.config.tts?.enabled ? 'on' : 'off'}`)
1234
+ }
1235
+
1236
+ if (cmd === '/mute') {
1237
+ this.setMuted(chatId, true)
1238
+ return reply(t('msg.muted_on', {}, locale))
1239
+ }
1240
+
1241
+ if (cmd === '/unmute') {
1242
+ this.setMuted(chatId, false)
1243
+ return reply(t('msg.muted_off', {}, locale))
1244
+ }
1245
+
1246
+ return reply(t('msg.unknown_command', { cmd }, locale))
1247
+ }
1248
+
1249
+ collectDynamicSkills() {
1250
+ const skills = []
1251
+ try {
1252
+ const skillsService = this.ctx.get?.('skills') || this.ctx.skills
1253
+ const allSkills = skillsService?.list?.() || []
1254
+ for (const s of allSkills) {
1255
+ if (!s || !s.name) continue
1256
+ if (s.userInvocable === false) continue
1257
+ skills.push({
1258
+ name: String(s.name),
1259
+ description: String(s.description || s.title || `Skill ${s.name}`).slice(0, 256),
1260
+ })
1261
+ }
1262
+ } catch (err) {
1263
+ this.ctx.logger?.debug?.(`Failed to collect dynamic skills: ${err?.message || err}`)
1264
+ }
1265
+ return skills
1266
+ }
1267
+
1268
+ async syncTelegramCommands() {
1269
+ const tgAdapter = this.adapters.get('telegram')
1270
+ if (!tgAdapter || typeof tgAdapter.registerCommands !== 'function') return
1271
+ const baseCommands = this.config.telegram?.commands || []
1272
+ const dynamicSkills = this.collectDynamicSkills()
1273
+ const merged = mergeDynamicCommands(baseCommands, dynamicSkills, 100)
1274
+ try {
1275
+ await tgAdapter.registerCommands(merged)
1276
+ this.ctx.logger?.info?.(`Synced ${merged.length} Telegram commands (including ${dynamicSkills.length} dynamic skills)`)
1277
+ } catch (err) {
1278
+ this.ctx.logger?.warn?.(`Failed to sync Telegram commands: ${err?.message || err}`)
1279
+ }
1280
+ }
1281
+
1282
+ async mirrorSessionToForumTopic(session) {
1283
+ if (!session || !session.id) return
1284
+ const sessionId = String(session.id)
1285
+ if (sessionId.startsWith('msgw-')) return
1286
+ if (this.sessionToThread.has(sessionId)) return
1287
+
1288
+ const tgCfg = this.config.telegram || {}
1289
+ if (!tgCfg.forumMirrorEnabled || !tgCfg.forumMirrorChatId) return
1290
+
1291
+ const tgAdapter = this.adapters.get('telegram')
1292
+ if (!tgAdapter || typeof tgAdapter.createForumTopic !== 'function') return
1293
+
1294
+ const forumChatId = tgCfg.forumMirrorChatId
1295
+ const title = String(session.title || session.meta?.name || `Session ${sessionId.slice(0, 8)}`).slice(0, 120)
1296
+
1297
+ try {
1298
+ const topic = await tgAdapter.createForumTopic(forumChatId, title)
1299
+ const threadId = topic?.message_thread_id
1300
+ if (!threadId) return
1301
+
1302
+ const threadKey = `${forumChatId}:${threadId}`
1303
+ this.sessionToThread.set(sessionId, { chatId: forumChatId, threadId })
1304
+ this.threadToSession.set(threadKey, sessionId)
1305
+
1306
+ const text = t('mirror.created', { sessionId, title }, 'en')
1307
+ await tgAdapter.sendTo(forumChatId, { text }, { threadId })
1308
+ this.ctx.logger?.info?.(`Mirrored session ${sessionId} to Telegram forum topic ${threadId} in ${forumChatId}`)
1309
+ } catch (err) {
1310
+ this.ctx.logger?.warn?.(`Failed to mirror session ${sessionId} to forum topic: ${err?.message || err}`)
1311
+ }
1312
+ }
1313
+
1314
+ async relayTurnToForumMirror(session, event) {
1315
+ if (!session || !session.id) return
1316
+ const sessionId = String(session.id)
1317
+ const threadInfo = this.sessionToThread.get(sessionId)
1318
+ if (!threadInfo) return
1319
+ if (this.pending.has(sessionId)) return
1320
+
1321
+ const tgAdapter = this.adapters.get('telegram')
1322
+ if (!tgAdapter) return
1323
+
1324
+ const messages = Array.isArray(session.messages)
1325
+ ? session.messages
1326
+ : (Array.isArray(session.history) ? session.history : [])
1327
+
1328
+ for (let i = messages.length - 1; i >= 0; i--) {
1329
+ const msg = messages[i]
1330
+ const role = msg.role || (msg.type === 'user' ? 'user' : 'assistant')
1331
+ if (role === 'assistant') {
1332
+ let text = ''
1333
+ if (typeof msg.content === 'string') text = msg.content
1334
+ else if (Array.isArray(msg.content)) {
1335
+ text = msg.content
1336
+ .map((p) => (typeof p === 'string' ? p : (p?.text || '')))
1337
+ .filter(Boolean)
1338
+ .join('\n')
1339
+ } else if (msg.text) text = msg.text
1340
+ const clean = stripReasoningPreamble(stripImageUrls(text)).trim()
1341
+ if (clean) {
1342
+ const maxLen = Number(this.config.agent?.maxMessageLength) || 4000
1343
+ const chunks = splitText(clean, maxLen)
1344
+ for (const chunk of chunks) {
1345
+ await tgAdapter.sendTo(threadInfo.chatId, { text: chunk }, { threadId: threadInfo.threadId })
1346
+ }
1347
+ }
1348
+ break
1349
+ }
1350
+ }
1351
+ }
1352
+
1353
+ async getOrCreateChat(key, input) {
1354
+ let chat = this.chats.get(key)
1355
+ if (!chat) {
1356
+ const threadKey = `${input.chatId}:${input.threadId || 0}`
1357
+ const existingSessionId = this.threadToSession.get(threadKey)
1358
+ chat = await this.createChat(key, input, existingSessionId)
1359
+ this.chats.set(key, chat)
1360
+ }
1361
+ chat.lastUsed = Date.now()
1362
+ chat.target = { platform: input.platform, chatId: input.chatId, threadId: input.threadId || 0 }
1363
+ return chat
1364
+ }
1365
+
1366
+ resolveAgentModel() {
1367
+ const agentCfg = this.config.agent || {}
1368
+ let provider = String(agentCfg.provider || '').trim()
1369
+ let model = String(agentCfg.model || '').trim()
1370
+ if (provider && model) return { provider, model }
1371
+ const selection = this.ctx.get('agentDefaultModel')?.currentSelection?.()
1372
+ if (!selection?.provider || !selection?.model) {
1373
+ throw new Error('Please select a model in Settings -> Models (or set agent.provider/model in profile)')
1374
+ }
1375
+ return { provider: provider || selection.provider, model: model || selection.model }
1376
+ }
1377
+
1378
+ async createChat(key, input, existingSessionId) {
1379
+ const { provider, model } = this.resolveAgentModel()
1380
+ const agentCfg = this.config.agent || {}
1381
+ const cwd = agentCfg.cwd || process.cwd()
1382
+ const self = this
1383
+ const agents = this.ctx.get?.('agents') || this.ctx.agents
1384
+ const targetSessionId = existingSessionId ? SessionId(existingSessionId) : SessionId(`msgw-${randomUUID()}`)
1385
+ const handle = await agents.create({
1386
+ sessionId: targetSessionId,
1387
+ meta: { cwd },
1388
+ agentOptions: { provider, model },
1389
+ setup: (agentCtx) => {
1390
+ installModelSelection(agentCtx, { current: { provider, model }, assembled: undefined })
1391
+ if (self.tg().approvalsEnabled !== false) {
1392
+ agentCtx.on('approval/request', (req, next) => self.answerApproval(key, req, next))
1393
+ }
1394
+ },
1395
+ })
1396
+ await handle.agent.whenIdle()
1397
+ const chat = {
1398
+ key, agent: handle.agent, dispose: handle.dispose, busy: Promise.resolve(),
1399
+ lastUsed: Date.now(), abort: undefined, pendingMedia: [], turnActive: false,
1400
+ sessionAllowlist: new Set(),
1401
+ target: input ? { platform: input.platform, chatId: input.chatId, threadId: input.threadId || 0 } : undefined,
1402
+ }
1403
+ this.sessionToChat.set(String(handle.agent.session.id), key)
1404
+ if (existingSessionId && input) {
1405
+ const threadKey = `${input.chatId}:${input.threadId || 0}`
1406
+ this.threadToSession.set(threadKey, existingSessionId)
1407
+ this.sessionToThread.set(existingSessionId, { chatId: input.chatId, threadId: input.threadId || 0 })
1408
+ }
1409
+ return chat
1410
+ }
1411
+
1412
+ async answerApproval(chatKeyValue, req, next) {
1413
+ try {
1414
+ const chat = this.chats.get(chatKeyValue)
1415
+ if (!chat?.target) return next()
1416
+ const tool = req.toolName || 'tool'
1417
+ if (chat.sessionAllowlist?.has(tool)) {
1418
+ return 'allowed-once'
1419
+ }
1420
+ const locale = this.resolveLocale(chat.target)
1421
+ const reason = req.reason ? `\n<i>${req.reason}</i>` : ''
1422
+ let detail = ''
1423
+ if (req.input && typeof req.input === 'object') {
1424
+ try {
1425
+ const jsonStr = JSON.stringify(req.input, null, 2)
1426
+ detail = `\n<pre><code>${jsonStr.slice(0, 500)}</code></pre>`
1427
+ } catch {}
1428
+ }
1429
+ const text = t('ask.confirm_title', { tool, reason: reason + detail }, locale)
1430
+ const buttons = [
1431
+ [
1432
+ { id: 'allow_once', text: t('ask.allow_once', {}, locale) },
1433
+ { id: 'allow_session', text: t('ask.allow_session', {}, locale) },
1434
+ { id: 'deny', text: t('ask.deny', {}, locale) },
1435
+ ],
1436
+ ]
1437
+ const result = await this.messengerAsk(chat.target, { text, buttons }, 300_000)
1438
+ if (result?.buttonId === 'allow_once' || result?.buttonId === 'allow') return 'allowed-once'
1439
+ if (result?.buttonId === 'allow_session') {
1440
+ if (!chat.sessionAllowlist) chat.sessionAllowlist = new Set()
1441
+ chat.sessionAllowlist.add(tool)
1442
+ return 'allowed-once'
1443
+ }
1444
+ if (result?.buttonId === 'deny') return 'rejected'
1445
+ return next()
1446
+ } catch {
1447
+ return next()
1448
+ }
1449
+ }
1450
+
1451
+ async buildUserContent(input, signal) {
1452
+ const { text, attachments = [], replyText, steer, personaOverride } = input
1453
+ const parts = []
1454
+ parts.push(String(this.config.agent?.instructionPrefix || MESSENGER_RELAY_INSTRUCTION))
1455
+ const activePersonaId = personaOverride || this.personas.getPersonaForChat(input.chatId, input.threadId)
1456
+ const activePersona = getPersona(activePersonaId)
1457
+ if (activePersona?.instruction) {
1458
+ parts.push(`[Persona: ${activePersona.name} (${activePersona.icon})]\n${activePersona.instruction}`)
1459
+ }
1460
+ if (steer) parts.push('[Steer / addition to current turn: combine with previous instruction, do not restart from scratch]')
1461
+ if (replyText?.trim()) parts.push(`[Replying to message: ${replyText.trim()}]`)
1462
+ const blocks = []
1463
+ for (const att of attachments) {
1464
+ if (att.kind === 'photo' || (att.kind === 'sticker' && att.mime?.startsWith('image/'))) {
1465
+ try {
1466
+ const { ref } = await attachInboundPhoto(this.ctx, att, {
1467
+ signal,
1468
+ maxBytes: Number(this.config.media?.maxImageBytes) || 20 * 1024 * 1024,
1469
+ })
1470
+ blocks.push({ type: 'image', attachment: ref })
1471
+ if (att.kind === 'sticker' && att.emoji) parts.push(`[Sticker ${att.emoji}]`)
1472
+ } catch (err) {
1473
+ if (signal?.aborted) throw err
1474
+ const msg = err instanceof Error ? err.message : String(err)
1475
+ parts.push(`[Failed to attach image: ${msg}]`)
1476
+ }
1477
+ } else if (att.kind === 'voice' || att.kind === 'audio') {
1478
+ try {
1479
+ const bytes = new Uint8Array(await readFile(att.path))
1480
+ const transcript = await transcribeVoice(this.baseUrl(), bytes, att.mime || 'audio/ogg', 'message', signal)
1481
+ parts.push(transcript ? `[Voice message transcript: ${transcript}]` : '[Voice message (unrecognized)]')
1482
+ } catch (err) {
1483
+ if (signal?.aborted) throw err
1484
+ const msg = err instanceof Error ? err.message : String(err)
1485
+ this.ctx.logger?.warn?.(`voice: ${msg}`)
1486
+ parts.push(`[Voice message (dsh-voice unavailable: ${msg})]`)
1487
+ }
1488
+ } else if (att.kind === 'document' || att.kind === 'video' || att.kind === 'animation' || att.kind === 'sticker') {
1489
+ let parsed = null
1490
+ if (att.kind === 'document' && att.path) {
1491
+ try {
1492
+ const maxDocBytes = Number(this.config.media?.maxTextInjectBytes) || 100 * 1024
1493
+ parsed = await parseDocument(att.path, { maxBytes: maxDocBytes })
1494
+ } catch {}
1495
+ }
1496
+ parts.push(formatInboundDocument(att, parsed))
1497
+ } else {
1498
+ parts.push(`[File: ${att.path}${att.name ? ` (${att.name})` : ''}]`)
1499
+ }
1500
+ }
1501
+ const photoHint = photoOnlyHint(attachments, text)
1502
+ if (photoHint) parts.push(photoHint)
1503
+ const docHint = documentOnlyHint(attachments, text)
1504
+ if (docHint) parts.push(docHint)
1505
+ if (text?.trim()) parts.push(text.trim())
1506
+ const textBlock = parts.filter(Boolean).join('\n\n')
1507
+ if (textBlock) blocks.unshift({ type: 'text', text: textBlock })
1508
+ if (!blocks.length) blocks.push({ type: 'text', text: '(empty message)' })
1509
+ return blocks
1510
+ }
1511
+
1512
+ async runTurn(chat, input, signal) {
1513
+ const { reply, typing, startStream, startProgress, react, inboundWasVoice, userId } = input
1514
+ chat.turnActive = true
1515
+ const sessionId = chat.agent.session.id
1516
+ const tg = this.tg()
1517
+ const streaming = tg.streaming === true && typeof startStream === 'function'
1518
+ const progressEnabled = tg.progressEnabled !== false
1519
+ const collector = { parts: [], lastText: '', streamText: '', toolName: '', images: [], reason: undefined, onStream: undefined }
1520
+ this.pending.set(sessionId, collector)
1521
+ let stopTyping = () => {}
1522
+ let stream = null
1523
+ let scheduler = null
1524
+ let progress = null
1525
+ try {
1526
+ if (signal.aborted) return
1527
+ if (typeof react === 'function' && tg.reactionsEnabled !== false) {
1528
+ react('👀').catch?.(() => {})
1529
+ }
1530
+ if (typeof typing === 'function') stopTyping = startTypingHeartbeat(typing, 4000)
1531
+ if (streaming) {
1532
+ try {
1533
+ stream = await startStream()
1534
+ scheduler = createEditScheduler((text) => stream.edit(text), Number(tg.streamEditIntervalMs) || 1200)
1535
+ collector.onStream = (text, toolName) => {
1536
+ if (text) stopTyping()
1537
+ if (!progressEnabled && !text) return
1538
+ scheduler.push(buildStreamPreview(text, progressEnabled ? toolName : ''))
1539
+ }
1540
+ if (progressEnabled) scheduler.push(buildStreamPreview('', ''))
1541
+ } catch (e) {
1542
+ this.ctx.logger?.warn?.(`stream start: ${e.message}`)
1543
+ stream = null
1544
+ }
1545
+ } else if (progressEnabled && typeof startProgress === 'function') {
1546
+ try {
1547
+ progress = await startProgress()
1548
+ const editProgress = createEditScheduler((text) => progress.edit(text), 800)
1549
+ collector.onStream = (_text, toolName) => {
1550
+ editProgress.push(formatProgressLine(toolName))
1551
+ }
1552
+ } catch (e) {
1553
+ this.ctx.logger?.warn?.(`progress start: ${e.message}`)
1554
+ progress = null
1555
+ }
1556
+ }
1557
+
1558
+
1559
+ const content = await this.buildUserContent(input, signal)
1560
+ chat.agent.followup(createUserMessage({
1561
+ content: ensureContentArray(content),
1562
+ source: { kind: 'user', plugin: PLUGIN, form: 'relay', origin: 'telegram' },
1563
+ }))
1564
+ const turnTimeoutMs = Number(this.config.agent?.turnTimeoutMs) || 600_000
1565
+ await whenIdleWithTimeout(chat.agent, turnTimeoutMs, signal)
1566
+ if (signal.aborted) {
1567
+ if (progress) try { await progress.remove() } catch {}
1568
+ if (typeof react === 'function') react('').catch?.(() => {})
1569
+ const stoppedMsg = t('msg.turn_stopped', {}, this.resolveLocale(input))
1570
+ if (stream) try { await stream.finalize(stoppedMsg) } catch {}
1571
+ else return reply(stoppedMsg)
1572
+ return
1573
+ }
1574
+ const sessions = this.ctx.get?.('sessions') || this.ctx.sessions
1575
+ await sessions?.flush?.(chat.agent.session)
1576
+ if (progress) try { await progress.remove() } catch {}
1577
+ progress = null
1578
+ if (typeof react === 'function') react('').catch?.(() => {})
1579
+ const rawAnswer = stripReasoningPreamble(stripImageUrls(collector.lastText || collector.streamText || collector.parts.join('\n\n')))
1580
+ const processed = processDiagramsAndTables(rawAnswer, {
1581
+ artifactPreviews: this.tg().artifactPreviews !== false,
1582
+ })
1583
+ const answer = processed.text
1584
+ if (collector.reason?.kind === 'error') {
1585
+ const err = collector.reason.error
1586
+ const msg = t('msg.agent_error', { code: err?.code || 'error', message: err?.message || 'unknown' }, this.resolveLocale(input))
1587
+ this.sendAlert('error', {
1588
+ code: err?.code || 'AGENT_ERROR',
1589
+ message: err?.message || 'unknown',
1590
+ sessionId,
1591
+ chatId: input.chatId,
1592
+ threadId: input.threadId,
1593
+ }).catch(() => {})
1594
+ if (stream) { await scheduler?.flush(); await stream.finalize(msg) }
1595
+ else await reply(msg)
1596
+ return
1597
+ }
1598
+ const files = await buildOutboundFiles(this.ctx, this.baseUrl(), collector, { signal, logger: this.ctx.logger })
1599
+ const allFiles = [...files, ...(processed.files || [])]
1600
+ if (!answer && !allFiles.length) {
1601
+ const noResp = t('msg.no_response', {}, this.resolveLocale(input))
1602
+ if (stream) { await scheduler?.flush(); await stream.finalize(noResp) }
1603
+ else await reply(noResp)
1604
+ return
1605
+ }
1606
+ const maxLen = Number(this.config.agent?.maxMessageLength) || 4000
1607
+ const chunks = answer ? splitText(answer, maxLen) : ['']
1608
+ if (stream) {
1609
+ await scheduler?.flush()
1610
+ await stream.finalize(chunks[0] || t('msg.no_response', {}, this.resolveLocale(input)))
1611
+ for (let i = 1; i < chunks.length; i++) await reply({ text: chunks[i] })
1612
+ if (allFiles.length) await reply({ files: allFiles })
1613
+ } else {
1614
+ for (let i = 0; i < chunks.length; i++) {
1615
+ await reply({ text: chunks[i] || undefined, files: i === 0 ? allFiles : [] })
1616
+ }
1617
+ }
1618
+ const chatTtsPref = this.chatTts.get(chat.target?.chatId)
1619
+ const speak = shouldSpeakReply({
1620
+ globalTts: Boolean(this.config.tts?.enabled),
1621
+ voiceMode: this.tg().voiceMode || 'mirror',
1622
+ inboundWasVoice: Boolean(inboundWasVoice),
1623
+ userPref: this.voicePrefs.get(userId),
1624
+ chatPref: chatTtsPref,
1625
+ })
1626
+ if (speak && !signal.aborted) {
1627
+ const isVoiceSummary = this.config.tts?.voiceSummary === true
1628
+ const ttsText = prepareTtsText(answer, this.config.tts?.maxChars, { voiceSummary: isVoiceSummary })
1629
+ if (ttsText) {
1630
+ try {
1631
+ const spoken = await speakText(this.baseUrl(), ttsText, signal)
1632
+ const voiceFile = await toTelegramVoiceFile(spoken, { logger: this.ctx.logger })
1633
+ if (!signal.aborted && voiceFile) await reply({ files: [voiceFile] })
1634
+ } catch (e) {
1635
+ if (!signal?.aborted) this.ctx.logger?.warn?.(`tts: ${e.message}`)
1636
+ }
1637
+ }
1638
+ }
1639
+ } catch (err) {
1640
+ if (!signal?.aborted) {
1641
+ this.sendAlert('error', {
1642
+ code: err?.code || 'EXCEPTION',
1643
+ message: err?.message || String(err),
1644
+ sessionId,
1645
+ chatId: input.chatId,
1646
+ threadId: input.threadId,
1647
+ }).catch(() => {})
1648
+ try {
1649
+ const excMsg = t('msg.exception', { message: err.message }, this.resolveLocale(input))
1650
+ if (stream) await stream.finalize(excMsg)
1651
+ else await reply(excMsg)
1652
+ } catch {}
1653
+ }
1654
+ } finally {
1655
+ stopTyping()
1656
+ if (progress) try { await progress.remove() } catch {}
1657
+ if (typeof react === 'function') react('').catch?.(() => {})
1658
+ chat.turnActive = false
1659
+ chat.abort = undefined
1660
+ this.pending.delete(sessionId)
1661
+ }
1662
+ }
1663
+
1664
+ reapIdle() {
1665
+ const rawTimeout = Number(this.config.agent?.idleTimeoutMs)
1666
+ const timeout = Number.isFinite(rawTimeout) && rawTimeout > 0 ? rawTimeout : 86_400_000
1667
+ const now = Date.now()
1668
+ for (const [key, chat] of this.chats) {
1669
+ if (!chat.turnActive && now - chat.lastUsed > timeout) {
1670
+ if (chat.agent?.session?.id) {
1671
+ this.sessionToChat.delete(String(chat.agent.session.id))
1672
+ }
1673
+ this.chats.delete(key)
1674
+ chat.dispose().catch(() => {})
1675
+ }
1676
+ }
1677
+ }
1678
+
1679
+ async approvePairingCode(code, actorUserId = 0) {
1680
+ const res = this.pairing.approveCode(code, actorUserId)
1681
+ if (!res.ok) return res
1682
+ const merged = this.effectiveAllowedIds()
1683
+ for (const a of this.adapterList) a.setAllowedUserIds?.(merged)
1684
+ try { await this.hooks?.persistAllowedUserIds?.(merged) } catch (e) {
1685
+ this.ctx.logger?.warn?.(`persist allowlist: ${e.message}`)
1686
+ }
1687
+ return { ...res, allowedUserIds: merged }
1688
+ }
1689
+
1690
+ rejectPairingCode(code) {
1691
+ return this.pairing.rejectCode(code)
1692
+ }
1693
+
1694
+ async probeTelegram(timeoutMs = 10000) {
1695
+ const adapter = this.getAdapter('telegram')
1696
+ if (!adapter) {
1697
+ return { ok: false, error: 'Telegram adapter not initialized' }
1698
+ }
1699
+ if (typeof adapter.probeHealth === 'function') {
1700
+ return adapter.probeHealth(timeoutMs)
1701
+ }
1702
+ return { ok: false, error: 'probeHealth not implemented on adapter' }
1703
+ }
1704
+
1705
+ getBotInfo() {
1706
+ const adapter = this.getAdapter('telegram')
1707
+ return {
1708
+ botId: adapter?.botId || 0,
1709
+ botUsername: adapter?.botUsername || '',
1710
+ pollingConflict: Boolean(adapter?.pollingConflict),
1711
+ }
1712
+ }
1713
+
1714
+ async messengerAskFromAgent(agent, payload, timeoutMs) {
1715
+ const sessionId = String(agent?.session?.id || '')
1716
+ const key = this.sessionToChat.get(sessionId)
1717
+ const chat = key ? this.chats.get(key) : null
1718
+ if (!chat?.target) throw new Error('messenger_ask: no telegram chat for this agent session')
1719
+ return this.messengerAsk(chat.target, payload, timeoutMs)
1720
+ }
1721
+
1722
+ get messenger() {
1723
+ return {
1724
+ adapters: () => [...this.adapters.keys()],
1725
+ activeChats: () => this.chats.size,
1726
+ home: (name) => this.resolveHomeTarget('telegram', name),
1727
+ homes: () => listHomes(this.tg()),
1728
+ pairingPending: () => this.pairing.listPending(),
1729
+ pairingApproved: () => this.pairing.listApproved(),
1730
+ send: (target, payload) => this.messengerSend(target, payload),
1731
+ ask: (target, payload, timeoutMs) => this.messengerAsk(target, payload, timeoutMs),
1732
+ progress: (target, payload) => this.messengerProgress(target, payload),
1733
+ probeTelegram: (timeoutMs) => this.probeTelegram(timeoutMs),
1734
+ getBotInfo: () => this.getBotInfo(),
1735
+ }
1736
+ }
1737
+ }