@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/client.js CHANGED
@@ -116,107 +116,107 @@ window.__ModuleLoader__.load({
116
116
  'stats.active_chats': 'Active Chats in Memory',
117
117
  }
118
118
 
119
- const ru = {
119
+ const zh = {
120
120
  title: 'Messenger gateway',
121
- description: 'Telegram-бот: текст, голос, фото, документы и интерактивные опросы.',
122
- 'settings.loading': 'Загрузка настроек Messenger gateway',
123
- 'settings.retry': 'Повторить попытку',
124
- 'settings.unavailable': 'Настройки недоступны (пространство хоста ещё не готово).',
125
- 'header.title': 'Шлюз Telegram и мессенджеров',
126
- 'header.sub': 'Мост между DeepSeek Harness и Telegram: сессии, steer, топики форума, инлайн-кнопки и голосовые ответы.',
127
- 'badge.online': 'Telegram онлайн (@{username})',
128
- 'badge.running': 'Работает',
129
- 'badge.stopped': 'Остановлен',
130
- 'badge.token_ok': 'Токен ✓',
131
- 'badge.token_missing': 'Токен отсутствует',
132
- 'badge.pairing_count': 'Сопряжение: {count}',
133
- 'badge.transport': 'Транспорт: {mode}',
134
- save: 'Сохранить изменения',
135
- saved: 'Настройки успешно сохранены',
136
- saving: 'Сохранение…',
137
- showAdvanced: '⚙️ Расширенные настройки подключения и polling',
138
- hideAdvanced: 'Скрыть расширенные настройки',
139
- telegram: 'Настройки бота Telegram',
140
- telegramSub: 'Ключи доступа, белый список пользователей и параметры доставки сообщений.',
141
- agent: 'Поведение агента и рассуждения',
142
- agentSub: 'Маршрутизация модели, дополнительные инструкции и таймаут хода.',
143
- media: 'Ограничения медиа и документов',
144
- mediaSub: 'Лимиты на извлечение текста и размер загружаемых файлов.',
145
- tts: 'Голосовые ответы (dsh-tts)',
146
- ttsSub: 'Синтез аудиоответов на голосовые сообщения в чате.',
147
- advanced: 'Параметры соединения и polling',
148
- botToken: 'Токен бота Telegram',
149
- botTokenHint: 'Получен от @BotFather. Оставьте пустым, чтобы сохранить текущий.',
150
- allowedIds: 'Разрешённые ID пользователей',
151
- allowedIdsHint: 'ID пользователей через запятую. Пусто = доступно всем (включено сопряжение по кодам).',
152
- textFormat: 'Форматирование текста',
153
- textFormatHtml: 'Markdown → Telegram HTML (рекомендуется)',
154
- textFormatPlain: 'Простой текст (без форматирования)',
155
- disableTelegram: 'Выключить Telegram-бота',
156
- enableTelegram: 'Включить Telegram-бота',
157
- provider: 'Провайдер по умолчанию',
158
- providerHint: 'Пусто = провайдер по умолчанию DSH',
159
- model: 'Модель по умолчанию',
160
- modelHint: 'Пусто = модель по умолчанию DSH',
161
- photoOnly: 'Поведение фото без подписи',
162
- photoPrompt: 'Ждать вопроса (рекомендуется)',
163
- photoRun: 'Отвечать сразу',
164
- instruction: 'Дополнительная инструкция агенту',
165
- instructionHint: 'Добавляется к каждому входящему сообщению из мессенджера',
166
- instructionPlaceholder: 'Пусто = встроенная инструкция (русский язык, лаконичный ответ)',
167
- maxMessageLength: 'Макс. длина ответа (символов)',
168
- turnTimeout: 'Таймаут хода агента (сек)',
169
- maxDocMb: 'Макс. размер документа (МБ)',
170
- maxImageMb: 'Макс. размер фото (МБ)',
171
- maxTextKb: 'Макс. объём текста из документа (КБ)',
172
- ttsEnable: 'Включить голосовые ответы (требуется dsh-tts)',
173
- ttsMaxChars: 'Макс. символов для озвучивания',
174
- pollTimeout: 'Таймаут Long Poll (сек)',
175
- pollInterval: 'Интервал Long Poll (мс)',
176
- idleTimeout: 'Таймаут неактивного чата (сек)',
177
- pairing: 'Запросы сопряжения и авторизация',
178
- pairingSub: 'Подтверждение доступа новых пользователей при ограниченном списке.',
179
- pairingEmpty: 'Нет ожидающих кодов сопряжения',
180
- pairingApprove: 'Одобрить',
181
- pairingReject: 'Отклонить',
182
- pairingRefresh: 'Обновить список',
183
- groupsEnable: 'Отвечать в группах и супергруппах',
184
- groupMention: 'В группах отвечать только на @упоминание, reply или /команду',
185
- reactionsEnable: 'Реакция 👀 пока агент думает',
186
- progressEnable: 'Индикатор прогресса (ДумаюУдалитьОтвет)',
187
- statusIndicator: 'Индикатор статуса (Online/Offline)',
188
- statusIndicatorHint: 'Меняет краткое описание бота в Telegram (видно всем).',
189
- transport: 'Режим транспорта',
190
- transportPoll: 'Long poll (getUpdates)',
121
+ description: 'Telegram 机器人:文本、语音、图片、文档和交互式询问。',
122
+ 'settings.loading': '正在加载 Messenger gateway 设置…',
123
+ 'settings.retry': '重试',
124
+ 'settings.unavailable': '设置不可用(主机命名空间未就绪)。',
125
+ 'header.title': 'Telegram 与多消息平台网关',
126
+ 'header.sub': 'DeepSeek Harness Telegram 之间的桥梁:会话、转向提示、论坛话题、内联按钮和可选语音。',
127
+ 'badge.online': 'Telegram 在线 (@{username})',
128
+ 'badge.running': '运行中',
129
+ 'badge.stopped': '已停止',
130
+ 'badge.token_ok': '令牌有效 ✓',
131
+ 'badge.token_missing': '缺少令牌',
132
+ 'badge.pairing_count': '配对: {count}',
133
+ 'badge.transport': '传输方式: {mode}',
134
+ save: '保存更改',
135
+ saved: '设置保存成功',
136
+ saving: '保存中…',
137
+ showAdvanced: '⚙️ 高级连接与轮询设置',
138
+ hideAdvanced: '隐藏高级设置',
139
+ telegram: 'Telegram 机器人设置',
140
+ telegramSub: '主机器人凭证、白名单与消息发送设置。',
141
+ agent: '智能体与推理行为',
142
+ agentSub: '模型路由、附加指令与轮次超时设置。',
143
+ media: '媒体与文件限制',
144
+ mediaSub: '文档提取与图片上传限制。',
145
+ tts: '语音回复 (dsh-tts)',
146
+ ttsSub: ' Telegram 语音消息合成语音回复。',
147
+ advanced: '连接与轮询内部设置',
148
+ botToken: 'Telegram 机器人令牌',
149
+ botTokenHint: ' @BotFather 获取。留空保持现有配置。',
150
+ allowedIds: '允许的 Telegram 用户 ID',
151
+ allowedIdsHint: '逗号分隔的用户 ID 列表。留空允许所有用户(启用配对请求)。',
152
+ textFormat: '文本格式化渲染',
153
+ textFormatHtml: 'Markdown → Telegram HTML (推荐)',
154
+ textFormatPlain: '纯文本 (无格式化)',
155
+ disableTelegram: '停用 Telegram 机器人',
156
+ enableTelegram: '启用 Telegram 机器人',
157
+ provider: '提供商覆盖',
158
+ providerHint: '留空使用 DSH 默认提供商',
159
+ model: '模型覆盖',
160
+ modelHint: '留空使用 DSH 默认模型',
161
+ photoOnly: '无附言图片处理方式',
162
+ photoPrompt: '等待问题 (推荐)',
163
+ photoRun: '立即回复',
164
+ instruction: '额外智能体指令',
165
+ instructionHint: '添加到每条来自网关的消息前',
166
+ instructionPlaceholder: '留空 = 内置指令',
167
+ maxMessageLength: '最大回复长度 (字符)',
168
+ turnTimeout: '智能体轮次超时 ()',
169
+ maxDocMb: '最大文档大小 (MB)',
170
+ maxImageMb: '最大图片大小 (MB)',
171
+ maxTextKb: '文档提取最大文本量 (KB)',
172
+ ttsEnable: '启用语音回复 ( dsh-tts)',
173
+ ttsMaxChars: '每条语音消息最大字数',
174
+ pollTimeout: '长轮询超时 ()',
175
+ pollInterval: '长轮询间隔 (毫秒)',
176
+ idleTimeout: '空闲会话超时 ()',
177
+ pairing: '配对请求与授权',
178
+ pairingSub: '受限白名单下授权新用户。',
179
+ pairingEmpty: '暂无待处理配对码',
180
+ pairingApprove: '批准',
181
+ pairingReject: '拒绝',
182
+ pairingRefresh: '刷新列表',
183
+ groupsEnable: '在群组和超级群组中响应',
184
+ groupMention: '群组中需 @提及、回复或 /命令',
185
+ reactionsEnable: '处理中添加 👀 表情反应',
186
+ progressEnable: '进度状态提示 (思考中删除最终回复)',
187
+ statusIndicator: '机器人状态描述指示器 (Online/Offline)',
188
+ statusIndicatorHint: '通过 Telegram API 设置机器人简介(所有人可见)。',
189
+ transport: 'Telegram 传输模式',
190
+ transportPoll: '长轮询 (getUpdates)',
191
191
  transportWebhook: 'Webhook (HTTPS)',
192
- webhookUrl: 'Публичный HTTPS URL webhook',
193
- webhookUrlHint: 'Публичный адрес, куда Telegram доставляет входящие обновления',
194
- webhookSecret: 'Секретный токен webhook',
195
- webhookSecretHint: 'Оставьте пустым, чтобы не менять текущий секрет',
196
- sessionScope: 'Сессии в группах',
197
- sessionScopeChat: 'Общая сессия на чат/топик',
198
- sessionScopeUser: 'Индивидуальная на пользователя (рекомендуется)',
199
- voiceMode: 'Режим голосовых ответов',
200
- voiceModeMirror: 'Как входящее (голос на голос)',
201
- voiceModeAlways: 'Всегда отвечать голосовым',
202
- voiceModeOff: 'Выключено (если не включено через /voice)',
203
- notifyBridge: 'Мост уведомлений → Telegram Home',
204
- notifyBridgeHint: 'Пересылка событий task_done/error из web-сессий в указанный канал/топик',
205
- notifyHome: 'Имя целевого канала (Home)',
206
- quickActions: 'Клавиатура быстрых действий (/new, /stop, /voice, /status)',
207
- artifactPreviews: 'Превью диаграмм и таблиц в Telegram',
208
- 'diag.title': '⚡ Диагностика и проверка связи (Smoke test)',
209
- 'diag.desc': 'Проверка подключения к Telegram Bot API, замер сетевой задержки и валидация имени бота.',
210
- 'diag.smoke_btn': 'Проверить соединение с Telegram (Ping)',
211
- 'diag.smoke_testing': 'Проверка связи с Telegram API…',
212
- 'diag.smoke_ok': 'Связь с Telegram API установлена! Задержка: {latency} мс (@{username}, ID: {id})',
213
- 'diag.smoke_err': 'Ошибка проверки связи: {error}',
214
- 'stats.title': '📊 Телеметрия шлюза и счётчики',
215
- 'stats.desc': 'Статистика реального времени работающего процесса шлюза.',
216
- 'stats.sent': 'Сообщений отправлено',
217
- 'stats.errors': 'Ошибок доставки',
218
- 'stats.uptime': 'Время работы шлюза',
219
- 'stats.active_chats': 'Активных чатов в памяти',
192
+ webhookUrl: '公开 Webhook HTTPS 地址',
193
+ webhookUrlHint: 'Telegram 投递更新的公开端点',
194
+ webhookSecret: 'Webhook 密钥令牌',
195
+ webhookSecretHint: '留空保持当前配置的密钥',
196
+ sessionScope: '群组会话范围',
197
+ sessionScopeChat: '每个聊天/话题共享',
198
+ sessionScopeUser: '每用户独立会话 (推荐)',
199
+ voiceMode: '语音回复模式',
200
+ voiceModeMirror: '镜像输入语音 (仅语音输入时回复语音)',
201
+ voiceModeAlways: '始终合成语音回复',
202
+ voiceModeOff: '关闭 (除非通过 /voice 启用)',
203
+ notifyBridge: '通知网桥 → Telegram Home',
204
+ notifyBridgeHint: ' Web 会话的 task_done/error 事件转发至指定频道/话题',
205
+ notifyHome: '目标频道名称 (Home)',
206
+ quickActions: '快捷操作键盘 (/new, /stop, /voice, /status)',
207
+ artifactPreviews: ' Telegram 中预览图表与表格',
208
+ 'diag.title': '⚡ 诊断与连通性检查 (Smoke test)',
209
+ 'diag.desc': '检查 Telegram Bot API 连接、测量延迟并验证机器人名称。',
210
+ 'diag.smoke_btn': '测试 Telegram 连接 (Ping)',
211
+ 'diag.smoke_testing': '正在连接 Telegram API…',
212
+ 'diag.smoke_ok': 'Telegram API 连接成功!延迟: {latency} 毫秒 (@{username}, ID: {id})',
213
+ 'diag.smoke_err': '连通性检查失败: {error}',
214
+ 'stats.title': '📊 网关遥测与计数器',
215
+ 'stats.desc': '运行中网关进程的实时统计。',
216
+ 'stats.sent': '已发送消息',
217
+ 'stats.errors': '发送错误数',
218
+ 'stats.uptime': '运行时间',
219
+ 'stats.active_chats': '内存中活跃聊天数',
220
220
  }
221
221
 
222
222
  function useActiveLocale(ctx) {
@@ -234,7 +234,7 @@ window.__ModuleLoader__.load({
234
234
  }
235
235
 
236
236
  function makeT(locale) {
237
- const DICT = String(locale || '').startsWith('ru') ? ru : en
237
+ const DICT = String(locale || '').startsWith('zh') ? zh : en
238
238
  return (key, params) => {
239
239
  let text = DICT[key] || en[key] || key
240
240
  if (params && typeof params === 'object') {
@@ -1243,20 +1243,20 @@ window.__ModuleLoader__.load({
1243
1243
  try {
1244
1244
  const loc = ctx?.get?.('locale') || ctx?.locale
1245
1245
  if (loc?.register) {
1246
- loc.register(NS, { en, ru })
1246
+ loc.register(NS, { en, zh })
1247
1247
  }
1248
1248
  } catch (taken) {
1249
- console.warn('[dsh-messenger-gateway] словарь уже зарегистрирован:', taken && taken.message)
1249
+ console.warn('[dsh-messenger-gateway] dictionary already registered:', taken && taken.message)
1250
1250
  }
1251
1251
  }, 'dsh-messenger-gateway: dictionaries')
1252
1252
  } else {
1253
1253
  const loc = ctx?.get?.('locale') || ctx?.locale
1254
1254
  if (loc?.register) {
1255
- loc.register(NS, { en, ru })
1255
+ loc.register(NS, { en, zh })
1256
1256
  }
1257
1257
  }
1258
1258
  } catch (err) {
1259
- console.warn('[dsh-messenger-gateway] ошибка регистрации словаря:', err && err.message)
1259
+ console.warn('[dsh-messenger-gateway] dictionary registration error:', err && err.message)
1260
1260
  }
1261
1261
 
1262
1262
  if (typeof ctx.effect === 'function') {
package/lib/commands.js CHANGED
@@ -1,47 +1,73 @@
1
- export const DEFAULT_TELEGRAM_COMMANDS = [
2
- { command: 'start', description: 'Подключение и приветствие' },
3
- { command: 'help', description: 'Список команд' },
4
- { command: 'new', description: 'Новая сессия агента' },
5
- { command: 'whoami', description: 'Показать ваш Telegram id' },
6
- { command: 'stop', description: 'Прервать текущий ответ' },
7
- { command: 'pair', description: 'Одобрить код сопряжения: /pair CODE' },
8
- { command: 'sethome', description: 'Home: /sethome [name]' },
9
- { command: 'home', description: 'Список home-каналов' },
10
- { command: 'model', description: 'Интерактивный выбор или смена модели' },
11
- { command: 'top', description: 'Ресурсы сервера: CPU, RAM, uptime, сессии' },
12
- { command: 'topic', description: 'Создать новый форум-топик под задачу: /topic <имя>' },
13
- { command: 'status', description: 'Статус шлюза' },
14
- { command: 'setalert', description: 'Назначить этот чат каналом алертов' },
15
- { command: 'alert', description: 'Статус канала алертов: /alert [test]' },
16
- { command: 'keyboard', description: 'Клавиатура быстрых действий: /keyboard on|off' },
17
- { command: 'role', description: 'Роль и персона агента: /role [name]' },
18
- { command: 'skills', description: 'Список активных инструментов и навыков' },
19
- { command: 'tools', description: 'Список активных инструментов' },
20
- { command: 'fork', description: 'Форк текущей сессии в новую ветку' },
21
- { command: 'export', description: 'Экспорт истории диалога в Markdown' },
22
- { command: 'rewind', description: 'Откат сообщений: /rewind [N]' },
23
- { command: 'files', description: 'Файловый менеджер рабочей папки: /files [dir]' },
24
- { command: 'get', description: 'Скачать файл в Telegram: /get <path>' },
25
- { command: 'remind', description: 'Напоминание: /remind <время> <текст>' },
26
- { command: 'voice', description: 'Голосовые ответы: /voice on|off|status' },
27
- { command: 'tts', description: 'Озвучка в этом чате: /tts on|off|status' },
28
- { command: 'mute', description: 'Не присылать уведомления в этот чат' },
29
- { command: 'unmute', description: 'Вернуть уведомления в этот чат' },
30
- ]
31
-
32
- export function normalizeTelegramCommands(commands) {
33
- const source = Array.isArray(commands) && commands.length ? commands : DEFAULT_TELEGRAM_COMMANDS
34
- const out = []
35
- const seen = new Set()
36
- for (const raw of source) {
37
- if (!raw || typeof raw !== 'object') continue
38
- let command = String(raw.command || '').trim().replace(/^\//, '')
39
- const description = String(raw.description || '').trim()
40
- if (!command || !description) continue
41
- command = command.slice(0, 32).toLowerCase()
42
- if (seen.has(command)) continue
43
- seen.add(command)
44
- out.push({ command, description: description.slice(0, 256) })
45
- }
46
- return out.length ? out : [...DEFAULT_TELEGRAM_COMMANDS]
47
- }
1
+ export const DEFAULT_TELEGRAM_COMMANDS = [
2
+ { command: 'start', description: 'Connect and show greeting' },
3
+ { command: 'help', description: 'Show commands help' },
4
+ { command: 'new', description: 'Start a new agent session' },
5
+ { command: 'whoami', description: 'Show your messenger user ID' },
6
+ { command: 'stop', description: 'Interrupt current turn' },
7
+ { command: 'pair', description: 'Approve pairing code: /pair CODE' },
8
+ { command: 'sethome', description: 'Set home: /sethome [name]' },
9
+ { command: 'home', description: 'List registered home channels' },
10
+ { command: 'model', description: 'Interactive model selector' },
11
+ { command: 'top', description: 'System resources: CPU, RAM, uptime' },
12
+ { command: 'topic', description: 'Create forum topic: /topic <name>' },
13
+ { command: 'status', description: 'Gateway and bot status' },
14
+ { command: 'setalert', description: 'Designate channel for alerts' },
15
+ { command: 'alert', description: 'Alert channel status: /alert [test]' },
16
+ { command: 'keyboard', description: 'Toggle quick actions: /keyboard on|off' },
17
+ { command: 'role', description: 'Switch persona: /role [name]' },
18
+ { command: 'bind', description: 'Bind preset/persona to forum topic: /bind <name>' },
19
+ { command: 'preset', description: 'Show or switch agent preset: /preset [name]' },
20
+ { command: 'cron', description: 'Manage recurring reports: /cron' },
21
+ { command: 'skills', description: 'List active tools & skills' },
22
+ { command: 'tools', description: 'List active tools' },
23
+ { command: 'fork', description: 'Fork session into new branch' },
24
+ { command: 'export', description: 'Export history to Markdown' },
25
+ { command: 'rewind', description: 'Rewind turns: /rewind [N]' },
26
+ { command: 'files', description: 'Workspace file explorer: /files [dir]' },
27
+ { command: 'get', description: 'Download file to messenger: /get <path>' },
28
+ { command: 'remind', description: 'Set reminder: /remind <time> <text>' },
29
+ { command: 'voice', description: 'Voice reply mode: /voice on|off|status' },
30
+ { command: 'tts', description: 'Speech in this chat: /tts on|off|status' },
31
+ { command: 'mute', description: 'Mute notifications in this chat' },
32
+ { command: 'unmute', description: 'Unmute notifications in this chat' },
33
+ ]
34
+
35
+ export function normalizeTelegramCommands(commands) {
36
+ const source = Array.isArray(commands) && commands.length ? commands : DEFAULT_TELEGRAM_COMMANDS
37
+ const out = []
38
+ const seen = new Set()
39
+ for (const raw of source) {
40
+ if (!raw || typeof raw !== 'object') continue
41
+ let command = String(raw.command || '').trim().replace(/^\//, '')
42
+ const description = String(raw.description || '').trim()
43
+ if (!command || !description) continue
44
+ command = command.slice(0, 32).toLowerCase()
45
+ if (seen.has(command)) continue
46
+ seen.add(command)
47
+ out.push({ command, description: description.slice(0, 256) })
48
+ }
49
+ return out.length ? out : [...DEFAULT_TELEGRAM_COMMANDS]
50
+ }
51
+
52
+ export function mergeDynamicCommands(baseCommands = DEFAULT_TELEGRAM_COMMANDS, dynamicCommands = [], maxTotal = 100) {
53
+ const normalizedBase = normalizeTelegramCommands(baseCommands)
54
+ const out = [...normalizedBase]
55
+ const seen = new Set(out.map((c) => c.command))
56
+
57
+ for (const item of dynamicCommands || []) {
58
+ if (out.length >= maxTotal) break
59
+ if (!item || typeof item !== 'object') continue
60
+ let command = String(item.command || item.name || '').trim().replace(/^\//, '').toLowerCase()
61
+ // Telegram format: lowercase alphanumeric and underscore only, 1-32 chars
62
+ command = command.replace(/[^a-z0-9_]/g, '_').slice(0, 32)
63
+ if (!command || seen.has(command)) continue
64
+ let description = String(item.description || item.title || `Skill ${command}`).trim()
65
+ if (!description) description = `Skill ${command}`
66
+ description = description.slice(0, 256)
67
+ seen.add(command)
68
+ out.push({ command, description })
69
+ }
70
+
71
+ return out.slice(0, maxTotal)
72
+ }
73
+
package/lib/config.js CHANGED
@@ -1,98 +1,104 @@
1
- import z from '@deepseek-ai/schemastery'
2
-
3
- const HomeEntry = z.object({
4
- name: z.string().default('default'),
5
- chatId: z.union([z.number(), z.string()]),
6
- threadId: z.number().default(0),
7
- })
8
-
9
- export const PluginConfig = z.object({
10
- enabled: z.boolean().default(true),
11
- internalBaseURL: z.string().default('http://127.0.0.1:3080'),
12
- telegram: z.object({
13
- enabled: z.boolean().default(false),
14
- botToken: z.string().role('secret').default(''),
15
- allowedUserIds: z.array(z.number()).default([]),
16
- pollTimeoutSeconds: z.number().default(50),
17
- pollIntervalMs: z.number().default(500),
18
- commands: z.array(z.object({
19
- command: z.string(),
20
- description: z.string(),
21
- })).default([]),
22
- textFormat: z.union([z.const('html'), z.const('plain')]).default('html').description('html: Markdown→Telegram HTML; plain: без разметки'),
23
- homeChatId: z.union([z.number(), z.string()]).default('').description('Legacy default home chatId'),
24
- homeThreadId: z.number().default(0),
25
- homes: z.array(HomeEntry).default([]).description('Named homes (forum topics / channels)'),
26
- pairingEnabled: z.boolean().default(true).description('Issue pairing codes to unknown users when allowlist is non-empty'),
27
- streaming: z.boolean().default(false).description('If true, edit one Telegram message while tokens arrive; default off'),
28
- streamEditIntervalMs: z.number().default(1200),
29
- progressEnabled: z.boolean().default(true),
30
- approvalsEnabled: z.boolean().default(true),
31
- groupsEnabled: z.boolean().default(true).description('Process group/supergroup messages'),
32
- groupRequireMention: z.boolean().default(true).description('In groups, only respond to @mention, reply-to-bot, or /commands'),
33
- reactionsEnabled: z.boolean().default(true).description('React with 👀 while processing a turn'),
34
- statusIndicator: z.boolean().default(false).description('Opt-in: set bot short description to Online/Offline (bots have no presence)'),
35
- statusOnline: z.string().default('Online'),
36
- statusOffline: z.string().default('Offline'),
37
- transport: z.union([z.const('poll'), z.const('webhook')]).default('poll'),
38
- webhookUrl: z.string().default(''),
39
- webhookSecret: z.string().role('secret').default(''),
40
- webhookPath: z.string().default('/dsh-messenger-gateway/telegram/webhook'),
41
- voiceMode: z.union([z.const('mirror'), z.const('always'), z.const('off')]).default('mirror')
42
- .description('mirror: TTS when inbound was voice; always/off override (per-user /voice wins)'),
43
- quickActions: z.boolean().default(false).description('Show quick actions keyboard in Telegram (/new, /stop, /voice, /status)'),
44
- artifactPreviews: z.boolean().default(true).description('Render diagrams and formatted tables as previews'),
45
- notifyBridge: z.object({
46
- enabled: z.boolean().default(false),
47
- events: z.array(z.string()).default(['task_done', 'error']),
48
- home: z.string().default('default'),
49
- excludeSessionPrefixes: z.array(z.string()).default(['msgw-']),
50
- }).default({ enabled: false }),
51
- alerts: z.object({
52
- enabled: z.boolean().default(false),
53
- chatId: z.union([z.number(), z.string()]).default(''),
54
- threadId: z.number().default(0),
55
- home: z.string().default(''),
56
- events: z.array(z.string()).default(['error', 'pairing']),
57
- }).default({ enabled: false }),
58
- }),
59
- discord: z.object({
60
- enabled: z.boolean().default(false),
61
- botToken: z.string().role('secret').default(''),
62
- webhookUrl: z.string().default(''),
63
- }).default({ enabled: false }),
64
- slack: z.object({
65
- enabled: z.boolean().default(false),
66
- botToken: z.string().role('secret').default(''),
67
- webhookUrl: z.string().default(''),
68
- }).default({ enabled: false }),
69
- webhooks: z.object({
70
- enabled: z.boolean().default(true),
71
- secret: z.string().role('secret').default(''),
72
- }).default({ enabled: true }),
73
- media: z.object({
74
- cacheDir: z.string().default(''),
75
- maxDocBytes: z.number().default(20 * 1024 * 1024),
76
- maxTextInjectBytes: z.number().default(100 * 1024),
77
- maxImageBytes: z.number().default(20 * 1024 * 1024),
78
- }),
79
- tts: z.object({
80
- enabled: z.boolean().default(false),
81
- maxChars: z.number().default(4000),
82
- voiceSummary: z.boolean().default(false).description('Speak concise TL;DR summary while full text is sent to chat'),
83
- }),
84
- agent: z.object({
85
- provider: z.string().default(''),
86
- model: z.string().default(''),
87
- cwd: z.string().default(''),
88
- instructionPrefix: z.string().default(''),
89
- maxMessageLength: z.number().default(4000),
90
- idleTimeoutMs: z.number().default(3_600_000),
91
- turnTimeoutMs: z.number().default(600_000),
92
- photoOnlyMode: z.union([z.const('prompt'), z.const('run')]).default('prompt'),
93
- sessionScope: z.union([z.const('chat'), z.const('user')]).default('user')
94
- .description('In groups: user = per-user session; chat = shared session for the chat/topic'),
95
- }),
96
- })
97
-
98
- export const Config = PluginConfig
1
+ import z from '@deepseek-ai/schemastery'
2
+
3
+ const HomeEntry = z.object({
4
+ name: z.string().default('default'),
5
+ chatId: z.union([z.number(), z.string()]),
6
+ threadId: z.number().default(0),
7
+ })
8
+
9
+ export const PluginConfig = z.object({
10
+ enabled: z.boolean().default(true),
11
+ internalBaseURL: z.string().default('http://127.0.0.1:3080'),
12
+ telegram: z.object({
13
+ enabled: z.boolean().default(false),
14
+ botToken: z.string().role('secret').default(''),
15
+ allowedUserIds: z.array(z.number()).default([]),
16
+ pollTimeoutSeconds: z.number().default(50),
17
+ pollIntervalMs: z.number().default(500),
18
+ commands: z.array(z.object({
19
+ command: z.string(),
20
+ description: z.string(),
21
+ })).default([]),
22
+ textFormat: z.union([z.const('html'), z.const('plain')]).default('html').description('html: Markdown→Telegram HTML; plain: unformatted plain text'),
23
+ homeChatId: z.union([z.number(), z.string()]).default('').description('Legacy default home chatId'),
24
+ homeThreadId: z.number().default(0),
25
+ homes: z.array(HomeEntry).default([]).description('Named homes (forum topics / channels)'),
26
+ pairingEnabled: z.boolean().default(true).description('Issue pairing codes to unknown users when allowlist is non-empty'),
27
+ streaming: z.boolean().default(false).description('If true, edit one Telegram message while tokens arrive; default off'),
28
+ streamEditIntervalMs: z.number().default(1200),
29
+ progressEnabled: z.boolean().default(true),
30
+ approvalsEnabled: z.boolean().default(true),
31
+ groupsEnabled: z.boolean().default(true).description('Process group/supergroup messages'),
32
+ groupRequireMention: z.boolean().default(true).description('In groups, only respond to @mention, reply-to-bot, or /commands'),
33
+ reactionsEnabled: z.boolean().default(true).description('React with 👀 while processing a turn'),
34
+ statusIndicator: z.boolean().default(false).description('Opt-in: set bot short description to Online/Offline (bots have no presence)'),
35
+ statusOnline: z.string().default('Online'),
36
+ statusOffline: z.string().default('Offline'),
37
+ transport: z.union([z.const('poll'), z.const('webhook')]).default('poll'),
38
+ webhookUrl: z.string().default(''),
39
+ webhookSecret: z.string().role('secret').default(''),
40
+ webhookPath: z.string().default('/dsh-messenger-gateway/telegram/webhook'),
41
+ voiceMode: z.union([z.const('mirror'), z.const('always'), z.const('off')]).default('mirror')
42
+ .description('mirror: TTS when inbound was voice; always/off override (per-user /voice wins)'),
43
+ quickActions: z.boolean().default(false).description('Show quick actions keyboard in Telegram (/new, /stop, /voice, /status)'),
44
+ artifactPreviews: z.boolean().default(true).description('Render diagrams and formatted tables as previews'),
45
+ notifyBridge: z.object({
46
+ enabled: z.boolean().default(false),
47
+ events: z.array(z.string()).default(['task_done', 'error']),
48
+ home: z.string().default('default'),
49
+ excludeSessionPrefixes: z.array(z.string()).default(['msgw-']),
50
+ }).default({ enabled: false }),
51
+ alerts: z.object({
52
+ enabled: z.boolean().default(false),
53
+ chatId: z.union([z.number(), z.string()]).default(''),
54
+ threadId: z.number().default(0),
55
+ home: z.string().default(''),
56
+ events: z.array(z.string()).default(['error', 'pairing']),
57
+ }).default({ enabled: false }),
58
+ forumMirror: z.object({
59
+ enabled: z.boolean().default(false),
60
+ chatId: z.union([z.number(), z.string()]).default(''),
61
+ }).default({ enabled: false }),
62
+ forumMirrorChatId: z.union([z.number(), z.string()]).default(''),
63
+ forumMirrorEnabled: z.boolean().default(false),
64
+ }),
65
+ discord: z.object({
66
+ enabled: z.boolean().default(false),
67
+ botToken: z.string().role('secret').default(''),
68
+ webhookUrl: z.string().default(''),
69
+ }).default({ enabled: false }),
70
+ slack: z.object({
71
+ enabled: z.boolean().default(false),
72
+ botToken: z.string().role('secret').default(''),
73
+ webhookUrl: z.string().default(''),
74
+ }).default({ enabled: false }),
75
+ webhooks: z.object({
76
+ enabled: z.boolean().default(true),
77
+ secret: z.string().role('secret').default(''),
78
+ }).default({ enabled: true }),
79
+ media: z.object({
80
+ cacheDir: z.string().default(''),
81
+ maxDocBytes: z.number().default(20 * 1024 * 1024),
82
+ maxTextInjectBytes: z.number().default(100 * 1024),
83
+ maxImageBytes: z.number().default(20 * 1024 * 1024),
84
+ }),
85
+ tts: z.object({
86
+ enabled: z.boolean().default(false),
87
+ maxChars: z.number().default(4000),
88
+ voiceSummary: z.boolean().default(false).description('Speak concise TL;DR summary while full text is sent to chat'),
89
+ }),
90
+ agent: z.object({
91
+ provider: z.string().default(''),
92
+ model: z.string().default(''),
93
+ cwd: z.string().default(''),
94
+ instructionPrefix: z.string().default(''),
95
+ maxMessageLength: z.number().default(4000),
96
+ idleTimeoutMs: z.number().default(3_600_000),
97
+ turnTimeoutMs: z.number().default(600_000),
98
+ photoOnlyMode: z.union([z.const('prompt'), z.const('run')]).default('prompt'),
99
+ sessionScope: z.union([z.const('chat'), z.const('user')]).default('user')
100
+ .description('In groups: user = per-user session; chat = shared session for the chat/topic'),
101
+ }),
102
+ })
103
+
104
+ export const Config = PluginConfig
@@ -1,14 +1,14 @@
1
- /**
2
- * Normalize any content value to ContentBlock[].
3
- * DSH core (dsh-llm) calls content.some() without Array.isArray guard,
4
- * so we must ensure every message we create or copy has array content.
5
- * Refs: #51
6
- */
7
- export function ensureContentArray(content) {
8
- if (Array.isArray(content)) return content
9
- if (typeof content === 'string') {
10
- return content ? [{ type: 'text', text: content }] : [{ type: 'text', text: '(пустое сообщение)' }]
11
- }
12
- if (content && typeof content === 'object' && content.type) return [content]
13
- return [{ type: 'text', text: String(content ?? '(пустое сообщение)') }]
14
- }
1
+ /**
2
+ * Normalize any content value to ContentBlock[].
3
+ * DSH core (dsh-llm) calls content.some() without Array.isArray guard,
4
+ * so we must ensure every message we create or copy has array content.
5
+ * Refs: #51
6
+ */
7
+ export function ensureContentArray(content) {
8
+ if (Array.isArray(content)) return content
9
+ if (typeof content === 'string') {
10
+ return content ? [{ type: 'text', text: content }] : [{ type: 'text', text: '(empty message)' }]
11
+ }
12
+ if (content && typeof content === 'object' && content.type) return [content]
13
+ return [{ type: 'text', text: String(content ?? '(empty message)') }]
14
+ }