@goodandready/dsh-messenger-gateway 0.4.14 → 0.4.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/README.ru.md +4 -0
- package/README.zh.md +1 -1
- package/lib/adapters/index.js +2 -0
- package/lib/adapters/telegram-inbound.js +144 -141
- package/lib/adapters/telegram.js +32 -7
- package/lib/client.js +26 -0
- package/lib/config.js +2 -0
- package/lib/file-manager.js +9 -0
- package/lib/gateway.js +4 -2
- package/lib/index.js +14 -7
- package/lib/proxy.js +63 -0
- package/lib/stream.js +2 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -45,6 +45,8 @@ Talk to your Harness agent from Telegram: text, voice, photos, documents, inline
|
|
|
45
45
|
## Features
|
|
46
46
|
|
|
47
47
|
- Long-poll or webhook Telegram bot
|
|
48
|
+
- Configurable proxy support: HTTP, HTTPS, SOCKS5, and SOCKS5h (`telegram.proxyUrl`)
|
|
49
|
+
- Custom Bot API root URL (`telegram.apiRoot`) for reverse proxies and local Bot API servers
|
|
48
50
|
- Multi-transport support: Telegram, Discord (Webhooks & Bot API), and Slack (Webhooks & Bot API)
|
|
49
51
|
- Allowlist + pairing codes
|
|
50
52
|
- Per-user or per-chat sessions (`sessionScope`)
|
|
@@ -140,6 +142,8 @@ In addition to Telegram, outbound messages can be dispatched to Discord and Slac
|
|
|
140
142
|
- `voiceMode`: `mirror` / `always` / `off` — when to speak replies (also `/voice`)
|
|
141
143
|
- `tts.enabled` / `tts.maxChars` — TTS gate and length cap
|
|
142
144
|
- `notifyBridge` — forward non-messenger web session events to a home
|
|
145
|
+
- `telegram.proxyUrl`: optional HTTP, HTTPS, or SOCKS5 proxy URL (`socks5://127.0.0.1:1080`, `http://127.0.0.1:8080`)
|
|
146
|
+
- `telegram.apiRoot`: optional custom Telegram Bot API base URL (default: `https://api.telegram.org`), for local Bot API servers or reverse proxies
|
|
143
147
|
- Bot token is a DSH secret field — never commit it
|
|
144
148
|
|
|
145
149
|
## Client UI & Settings Card
|
package/README.ru.md
CHANGED
|
@@ -105,6 +105,10 @@ graph LR
|
|
|
105
105
|
* `/model` — просмотр и переключение активной модели агента;
|
|
106
106
|
* `/help` — список возможностей.
|
|
107
107
|
|
|
108
|
+
### 7. 🌐 Поддержка прокси и кастомного Bot API (`proxy.js`)
|
|
109
|
+
* Маршрутизация запросов к Telegram через прокси: HTTP, HTTPS, SOCKS5 и SOCKS5h (`telegram.proxyUrl`);
|
|
110
|
+
* Поддержка пользовательского базового адреса API (`telegram.apiRoot`) для локальных серверов Telegram Bot API или обратных прокси (reverse proxy).
|
|
111
|
+
|
|
108
112
|
---
|
|
109
113
|
|
|
110
114
|
## 📦 Быстрая установка
|
package/README.zh.md
CHANGED
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
|
|
40
40
|
**`dsh-messenger-gateway`** 为 **DeepSeek Harness** 智能体提供企业级 Telegram 接入桥梁。
|
|
41
41
|
|
|
42
|
-
除常规对话转发外,本插件全面打通了智能体深度交互能力:**问答交互式内联按钮 (Inline Keyboard)**、**Telegram 论坛话题 (Forum Topics)
|
|
42
|
+
除常规对话转发外,本插件全面打通了智能体深度交互能力:**问答交互式内联按钮 (Inline Keyboard)**、**Telegram 论坛话题 (Forum Topics) 独立会话隔离**、**代理连接支持 (HTTP/HTTPS/SOCKS5 与自定义 apiRoot)**、**单用户工作区目录安全隔离**、**6 位配对码鉴权防护**以及**语音条朗读回复 (TTS)**。
|
|
43
43
|
|
|
44
44
|
```mermaid
|
|
45
45
|
graph LR
|
package/lib/adapters/index.js
CHANGED
|
@@ -23,6 +23,8 @@ export default function createAdapters(deps) {
|
|
|
23
23
|
transport: tg.transport,
|
|
24
24
|
webhookUrl: tg.webhookUrl,
|
|
25
25
|
webhookSecret: tg.webhookSecret,
|
|
26
|
+
proxyUrl: tg.proxyUrl,
|
|
27
|
+
apiRoot: tg.apiRoot,
|
|
26
28
|
quickActions: tg.quickActions !== false,
|
|
27
29
|
artifactPreviews: tg.artifactPreviews !== false,
|
|
28
30
|
media: config.media,
|
|
@@ -1,141 +1,144 @@
|
|
|
1
|
-
import { basename } from 'node:path'
|
|
2
|
-
import {
|
|
3
|
-
IMAGE_EXT_TO_MIME, VIDEO_EXT_TO_MIME, classifyDocument,
|
|
4
|
-
extOf, TELEGRAM_MAX_DOC_BYTES,
|
|
5
|
-
} from '../media.js'
|
|
6
|
-
import { TEXT_INJECT_EXTS } from '../documents.js'
|
|
7
|
-
|
|
8
|
-
export async function extractTelegramInboundMedia(adapter, msg, initialText, maxDocBytes = TELEGRAM_MAX_DOC_BYTES, maxTextInjectBytes = 100 * 1024) {
|
|
9
|
-
let text = initialText || ''
|
|
10
|
-
const attachments = []
|
|
11
|
-
|
|
12
|
-
if (msg.photo?.length) {
|
|
13
|
-
const largest = msg.photo[msg.photo.length - 1]
|
|
14
|
-
const { path, file } = await adapter.downloadByFileId(largest.file_id, 'photo', extOf('', '') || '.jpg')
|
|
15
|
-
const ext = extOf(file.file_path, '') || '.jpg'
|
|
16
|
-
attachments.push({ kind: 'photo', path, mime: IMAGE_EXT_TO_MIME[ext] || 'image/jpeg' })
|
|
17
|
-
}
|
|
18
|
-
if (msg.sticker) {
|
|
19
|
-
const st = msg.sticker
|
|
20
|
-
if (st.is_video) {
|
|
21
|
-
try {
|
|
22
|
-
const { path } = await adapter.downloadByFileId(st.file_id, 'sticker-video', '.webm', st.file_unique_id || '')
|
|
23
|
-
attachments.push({ kind: 'animation', path, mime: 'video/webm', emoji: st.emoji || '', name: `sticker${st.emoji || ''}.webm` })
|
|
24
|
-
if (st.emoji) text = `${text}\n[Video sticker ${st.emoji}]`.trim()
|
|
25
|
-
} catch (e) {
|
|
26
|
-
text = `${text}\n[Video sticker ${st.emoji || ''} (download failed: ${e.message})]`.trim()
|
|
27
|
-
}
|
|
28
|
-
} else if (st.is_animated) {
|
|
29
|
-
try {
|
|
30
|
-
const { path } = await adapter.downloadByFileId(st.file_id, 'sticker-anim', '.tgs', st.file_unique_id || '')
|
|
31
|
-
attachments.push({ kind: 'document', path, mime: 'application/x-tgsticker', emoji: st.emoji || '', name: `sticker${st.emoji || ''}.tgs` })
|
|
32
|
-
if (st.emoji) text = `${text}\n[Animated sticker ${st.emoji}]`.trim()
|
|
33
|
-
} catch (e) {
|
|
34
|
-
text = `${text}\n[Animated sticker ${st.emoji || ''} (download failed: ${e.message})]`.trim()
|
|
35
|
-
}
|
|
36
|
-
} else {
|
|
37
|
-
const { path } = await adapter.downloadByFileId(st.file_id, 'sticker', '.webp', st.file_unique_id || '')
|
|
38
|
-
attachments.push({ kind: 'sticker', path, mime: 'image/webp', emoji: st.emoji || '', name: `sticker${st.emoji || ''}.webp` })
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
if (msg.voice) {
|
|
42
|
-
const { path } = await adapter.downloadByFileId(msg.voice.file_id, 'voice', '.ogg')
|
|
43
|
-
attachments.push({ kind: 'voice', path, mime: 'audio/ogg' })
|
|
44
|
-
}
|
|
45
|
-
if (msg.audio) {
|
|
46
|
-
const ext = extOf(msg.audio.file_name, msg.audio.mime_type) || '.mp3'
|
|
47
|
-
const { path } = await adapter.downloadByFileId(msg.audio.file_id, 'audio', ext, msg.audio.file_name || '')
|
|
48
|
-
attachments.push({ kind: 'audio', path, mime: msg.audio.mime_type || 'audio/mpeg' })
|
|
49
|
-
}
|
|
50
|
-
if (msg.video) {
|
|
51
|
-
const ext = extOf(msg.video.file_name, msg.video.mime_type) || '.mp4'
|
|
52
|
-
if ((msg.video.file_size || 0) > maxDocBytes) {
|
|
53
|
-
text = `${text}\n[Video too large]`.trim()
|
|
54
|
-
} else {
|
|
55
|
-
const { path } = await adapter.downloadByFileId(msg.video.file_id, 'video', ext, msg.video.file_name || '')
|
|
56
|
-
attachments.push({ kind: 'video', path, mime: msg.video.mime_type || VIDEO_EXT_TO_MIME[ext] || 'video/mp4', name: msg.video.file_name || basename(path) })
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
if (msg.video_note) {
|
|
60
|
-
const vn = msg.video_note
|
|
61
|
-
if ((vn.file_size || 0) > maxDocBytes) {
|
|
62
|
-
text = `${text}\n[Video note too large]`.trim()
|
|
63
|
-
} else {
|
|
64
|
-
const { path } = await adapter.downloadByFileId(vn.file_id, 'videonote', '.mp4')
|
|
65
|
-
attachments.push({ kind: 'video', path, mime: 'video/mp4', name: 'video_note.mp4' })
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
if (msg.animation) {
|
|
69
|
-
const an = msg.animation
|
|
70
|
-
const ext = extOf(an.file_name, an.mime_type) || '.mp4'
|
|
71
|
-
if ((an.file_size || 0) > maxDocBytes) {
|
|
72
|
-
text = `${text}\n[Animation too large]`.trim()
|
|
73
|
-
} else {
|
|
74
|
-
const { path } = await adapter.downloadByFileId(an.file_id, 'anim', ext, an.file_name || '')
|
|
75
|
-
attachments.push({ kind: 'animation', path, mime: an.mime_type || 'video/mp4', name: an.file_name || basename(path) })
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
if (msg.document) {
|
|
79
|
-
const doc = msg.document
|
|
80
|
-
const ext = extOf(doc.file_name, doc.mime_type)
|
|
81
|
-
const kind = classifyDocument(ext, doc.mime_type)
|
|
82
|
-
if (doc.file_size > maxDocBytes) {
|
|
83
|
-
text = `${text}\n[Document too large: ${doc.file_name || 'file'}]`.trim()
|
|
84
|
-
} else if (kind === 'unsupported') {
|
|
85
|
-
const { path } = await adapter.downloadByFileId(doc.file_id, 'doc', ext, doc.file_name || '')
|
|
86
|
-
attachments.push({ kind: 'document', path, mime: doc.mime_type || 'application/octet-stream', name: doc.file_name || basename(path) })
|
|
87
|
-
} else {
|
|
88
|
-
const { path, bytes } = await adapter.downloadByFileId(doc.file_id, 'doc', ext, doc.file_name || '')
|
|
89
|
-
if (kind === 'image') attachments.push({ kind: 'photo', path, mime: IMAGE_EXT_TO_MIME[ext] || doc.mime_type || 'image/jpeg', name: doc.file_name })
|
|
90
|
-
else if (kind === 'video') attachments.push({ kind: 'video', path, mime: VIDEO_EXT_TO_MIME[ext] || doc.mime_type || 'video/mp4', name: doc.file_name })
|
|
91
|
-
else if (bytes.length <= maxTextInjectBytes && TEXT_INJECT_EXTS.has(ext)) {
|
|
92
|
-
const body = new TextDecoder('utf-8', { fatal: false }).decode(bytes).slice(0, maxTextInjectBytes)
|
|
93
|
-
text = `${text}\n\n[Document ${doc.file_name}]\n${body}`.trim()
|
|
94
|
-
} else attachments.push({ kind: 'document', path, mime: doc.mime_type || 'application/octet-stream', name: doc.file_name || basename(path) })
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
return { text, attachments }
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
export async function probeTelegramHealth(adapter, timeoutMs = 10000) {
|
|
103
|
-
if (!adapter.token) {
|
|
104
|
-
return { ok: false, error: 'Telegram bot token is empty' }
|
|
105
|
-
}
|
|
106
|
-
const start = Date.now()
|
|
107
|
-
try {
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
1
|
+
import { basename } from 'node:path'
|
|
2
|
+
import {
|
|
3
|
+
IMAGE_EXT_TO_MIME, VIDEO_EXT_TO_MIME, classifyDocument,
|
|
4
|
+
extOf, TELEGRAM_MAX_DOC_BYTES,
|
|
5
|
+
} from '../media.js'
|
|
6
|
+
import { TEXT_INJECT_EXTS } from '../documents.js'
|
|
7
|
+
|
|
8
|
+
export async function extractTelegramInboundMedia(adapter, msg, initialText, maxDocBytes = TELEGRAM_MAX_DOC_BYTES, maxTextInjectBytes = 100 * 1024) {
|
|
9
|
+
let text = initialText || ''
|
|
10
|
+
const attachments = []
|
|
11
|
+
|
|
12
|
+
if (msg.photo?.length) {
|
|
13
|
+
const largest = msg.photo[msg.photo.length - 1]
|
|
14
|
+
const { path, file } = await adapter.downloadByFileId(largest.file_id, 'photo', extOf('', '') || '.jpg')
|
|
15
|
+
const ext = extOf(file.file_path, '') || '.jpg'
|
|
16
|
+
attachments.push({ kind: 'photo', path, mime: IMAGE_EXT_TO_MIME[ext] || 'image/jpeg' })
|
|
17
|
+
}
|
|
18
|
+
if (msg.sticker) {
|
|
19
|
+
const st = msg.sticker
|
|
20
|
+
if (st.is_video) {
|
|
21
|
+
try {
|
|
22
|
+
const { path } = await adapter.downloadByFileId(st.file_id, 'sticker-video', '.webm', st.file_unique_id || '')
|
|
23
|
+
attachments.push({ kind: 'animation', path, mime: 'video/webm', emoji: st.emoji || '', name: `sticker${st.emoji || ''}.webm` })
|
|
24
|
+
if (st.emoji) text = `${text}\n[Video sticker ${st.emoji}]`.trim()
|
|
25
|
+
} catch (e) {
|
|
26
|
+
text = `${text}\n[Video sticker ${st.emoji || ''} (download failed: ${e.message})]`.trim()
|
|
27
|
+
}
|
|
28
|
+
} else if (st.is_animated) {
|
|
29
|
+
try {
|
|
30
|
+
const { path } = await adapter.downloadByFileId(st.file_id, 'sticker-anim', '.tgs', st.file_unique_id || '')
|
|
31
|
+
attachments.push({ kind: 'document', path, mime: 'application/x-tgsticker', emoji: st.emoji || '', name: `sticker${st.emoji || ''}.tgs` })
|
|
32
|
+
if (st.emoji) text = `${text}\n[Animated sticker ${st.emoji}]`.trim()
|
|
33
|
+
} catch (e) {
|
|
34
|
+
text = `${text}\n[Animated sticker ${st.emoji || ''} (download failed: ${e.message})]`.trim()
|
|
35
|
+
}
|
|
36
|
+
} else {
|
|
37
|
+
const { path } = await adapter.downloadByFileId(st.file_id, 'sticker', '.webp', st.file_unique_id || '')
|
|
38
|
+
attachments.push({ kind: 'sticker', path, mime: 'image/webp', emoji: st.emoji || '', name: `sticker${st.emoji || ''}.webp` })
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (msg.voice) {
|
|
42
|
+
const { path } = await adapter.downloadByFileId(msg.voice.file_id, 'voice', '.ogg')
|
|
43
|
+
attachments.push({ kind: 'voice', path, mime: 'audio/ogg' })
|
|
44
|
+
}
|
|
45
|
+
if (msg.audio) {
|
|
46
|
+
const ext = extOf(msg.audio.file_name, msg.audio.mime_type) || '.mp3'
|
|
47
|
+
const { path } = await adapter.downloadByFileId(msg.audio.file_id, 'audio', ext, msg.audio.file_name || '')
|
|
48
|
+
attachments.push({ kind: 'audio', path, mime: msg.audio.mime_type || 'audio/mpeg' })
|
|
49
|
+
}
|
|
50
|
+
if (msg.video) {
|
|
51
|
+
const ext = extOf(msg.video.file_name, msg.video.mime_type) || '.mp4'
|
|
52
|
+
if ((msg.video.file_size || 0) > maxDocBytes) {
|
|
53
|
+
text = `${text}\n[Video too large]`.trim()
|
|
54
|
+
} else {
|
|
55
|
+
const { path } = await adapter.downloadByFileId(msg.video.file_id, 'video', ext, msg.video.file_name || '')
|
|
56
|
+
attachments.push({ kind: 'video', path, mime: msg.video.mime_type || VIDEO_EXT_TO_MIME[ext] || 'video/mp4', name: msg.video.file_name || basename(path) })
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (msg.video_note) {
|
|
60
|
+
const vn = msg.video_note
|
|
61
|
+
if ((vn.file_size || 0) > maxDocBytes) {
|
|
62
|
+
text = `${text}\n[Video note too large]`.trim()
|
|
63
|
+
} else {
|
|
64
|
+
const { path } = await adapter.downloadByFileId(vn.file_id, 'videonote', '.mp4')
|
|
65
|
+
attachments.push({ kind: 'video', path, mime: 'video/mp4', name: 'video_note.mp4' })
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (msg.animation) {
|
|
69
|
+
const an = msg.animation
|
|
70
|
+
const ext = extOf(an.file_name, an.mime_type) || '.mp4'
|
|
71
|
+
if ((an.file_size || 0) > maxDocBytes) {
|
|
72
|
+
text = `${text}\n[Animation too large]`.trim()
|
|
73
|
+
} else {
|
|
74
|
+
const { path } = await adapter.downloadByFileId(an.file_id, 'anim', ext, an.file_name || '')
|
|
75
|
+
attachments.push({ kind: 'animation', path, mime: an.mime_type || 'video/mp4', name: an.file_name || basename(path) })
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (msg.document) {
|
|
79
|
+
const doc = msg.document
|
|
80
|
+
const ext = extOf(doc.file_name, doc.mime_type)
|
|
81
|
+
const kind = classifyDocument(ext, doc.mime_type)
|
|
82
|
+
if (doc.file_size > maxDocBytes) {
|
|
83
|
+
text = `${text}\n[Document too large: ${doc.file_name || 'file'}]`.trim()
|
|
84
|
+
} else if (kind === 'unsupported') {
|
|
85
|
+
const { path } = await adapter.downloadByFileId(doc.file_id, 'doc', ext, doc.file_name || '')
|
|
86
|
+
attachments.push({ kind: 'document', path, mime: doc.mime_type || 'application/octet-stream', name: doc.file_name || basename(path) })
|
|
87
|
+
} else {
|
|
88
|
+
const { path, bytes } = await adapter.downloadByFileId(doc.file_id, 'doc', ext, doc.file_name || '')
|
|
89
|
+
if (kind === 'image') attachments.push({ kind: 'photo', path, mime: IMAGE_EXT_TO_MIME[ext] || doc.mime_type || 'image/jpeg', name: doc.file_name })
|
|
90
|
+
else if (kind === 'video') attachments.push({ kind: 'video', path, mime: VIDEO_EXT_TO_MIME[ext] || doc.mime_type || 'video/mp4', name: doc.file_name })
|
|
91
|
+
else if (bytes.length <= maxTextInjectBytes && TEXT_INJECT_EXTS.has(ext)) {
|
|
92
|
+
const body = new TextDecoder('utf-8', { fatal: false }).decode(bytes).slice(0, maxTextInjectBytes)
|
|
93
|
+
text = `${text}\n\n[Document ${doc.file_name}]\n${body}`.trim()
|
|
94
|
+
} else attachments.push({ kind: 'document', path, mime: doc.mime_type || 'application/octet-stream', name: doc.file_name || basename(path) })
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
return { text, attachments }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function probeTelegramHealth(adapter, timeoutMs = 10000) {
|
|
103
|
+
if (!adapter.token) {
|
|
104
|
+
return { ok: false, error: 'Telegram bot token is empty' }
|
|
105
|
+
}
|
|
106
|
+
const start = Date.now()
|
|
107
|
+
try {
|
|
108
|
+
const apiRoot = adapter.apiRoot || 'https://api.telegram.org'
|
|
109
|
+
const fetchOpts = {
|
|
110
|
+
method: 'POST',
|
|
111
|
+
headers: { 'Content-Type': 'application/json' },
|
|
112
|
+
body: JSON.stringify({}),
|
|
113
|
+
signal: AbortSignal.timeout(Math.max(1000, Number(timeoutMs) || 10000)),
|
|
114
|
+
}
|
|
115
|
+
if (adapter.dispatcher) fetchOpts.dispatcher = adapter.dispatcher
|
|
116
|
+
const res = await fetch(`${apiRoot}/bot${adapter.token}/getMe`, fetchOpts)
|
|
117
|
+
const latencyMs = Date.now() - start
|
|
118
|
+
const json = await res.json().catch(() => ({}))
|
|
119
|
+
if (!res.ok || json.ok === false) {
|
|
120
|
+
return {
|
|
121
|
+
ok: false,
|
|
122
|
+
latencyMs,
|
|
123
|
+
error: json.description || `HTTP ${res.status}`,
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const me = json.result || {}
|
|
127
|
+
adapter.botId = Number(me.id) || adapter.botId
|
|
128
|
+
adapter.botUsername = String(me.username || adapter.botUsername)
|
|
129
|
+
return {
|
|
130
|
+
ok: true,
|
|
131
|
+
latencyMs,
|
|
132
|
+
botId: adapter.botId,
|
|
133
|
+
botUsername: adapter.botUsername,
|
|
134
|
+
firstName: me.first_name || '',
|
|
135
|
+
}
|
|
136
|
+
} catch (err) {
|
|
137
|
+
return {
|
|
138
|
+
ok: false,
|
|
139
|
+
latencyMs: Date.now() - start,
|
|
140
|
+
error: err instanceof Error ? err.message : String(err),
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
package/lib/adapters/telegram.js
CHANGED
|
@@ -13,8 +13,8 @@ import {
|
|
|
13
13
|
} from '../groups.js'
|
|
14
14
|
import { isResendSafeNetworkError, isPollingConflict, isTopicGoneError, computePollBackoffMs } from '../telegram-errors.js'
|
|
15
15
|
import { extractTelegramInboundMedia, probeTelegramHealth } from './telegram-inbound.js'
|
|
16
|
+
import { createTelegramDispatcher, normalizeApiRoot } from '../proxy.js'
|
|
16
17
|
|
|
17
|
-
const API = 'https://api.telegram.org'
|
|
18
18
|
const TELEGRAM_MAX = 4096
|
|
19
19
|
|
|
20
20
|
import { buildQuickActionsKeyboard, REMOVE_REPLY_KEYBOARD } from '../commands.js'
|
|
@@ -55,6 +55,18 @@ export class TelegramAdapter {
|
|
|
55
55
|
this.pollTimer = undefined
|
|
56
56
|
this.botId = 0
|
|
57
57
|
this.botUsername = ''
|
|
58
|
+
this.apiRoot = normalizeApiRoot(opts.apiRoot)
|
|
59
|
+
this.proxyUrl = String(opts.proxyUrl || '').trim()
|
|
60
|
+
if (opts.dispatcher) {
|
|
61
|
+
this.dispatcher = opts.dispatcher
|
|
62
|
+
this.ownDispatcher = null
|
|
63
|
+
} else if (this.proxyUrl) {
|
|
64
|
+
this.dispatcher = createTelegramDispatcher(this.proxyUrl, { logger: this.logger })
|
|
65
|
+
this.ownDispatcher = this.dispatcher
|
|
66
|
+
} else {
|
|
67
|
+
this.dispatcher = null
|
|
68
|
+
this.ownDispatcher = null
|
|
69
|
+
}
|
|
58
70
|
}
|
|
59
71
|
|
|
60
72
|
setAllowedUserIds(ids) {
|
|
@@ -63,13 +75,15 @@ export class TelegramAdapter {
|
|
|
63
75
|
|
|
64
76
|
async call(method, params = {}) {
|
|
65
77
|
const timeoutMs = (this.timeoutSeconds * 1000) + 15000
|
|
66
|
-
const
|
|
78
|
+
const fetchOpts = {
|
|
67
79
|
method: 'POST',
|
|
68
80
|
headers: { 'Content-Type': 'application/json' },
|
|
69
81
|
body: JSON.stringify(params),
|
|
70
82
|
keepalive: true,
|
|
71
83
|
signal: AbortSignal.timeout(timeoutMs),
|
|
72
|
-
}
|
|
84
|
+
}
|
|
85
|
+
if (this.dispatcher) fetchOpts.dispatcher = this.dispatcher
|
|
86
|
+
const res = await fetch(`${this.apiRoot}/bot${this.token}/${method}`, fetchOpts)
|
|
73
87
|
const json = await res.json().catch(() => ({}))
|
|
74
88
|
if (!res.ok || json.ok === false) throw new Error(`telegram ${method}: ${json.description || res.status}`)
|
|
75
89
|
return json.result
|
|
@@ -77,12 +91,14 @@ export class TelegramAdapter {
|
|
|
77
91
|
|
|
78
92
|
async callMultipart(method, form) {
|
|
79
93
|
const timeoutMs = (this.timeoutSeconds * 1000) + 30000
|
|
80
|
-
const
|
|
94
|
+
const fetchOpts = {
|
|
81
95
|
method: 'POST',
|
|
82
96
|
body: form,
|
|
83
97
|
keepalive: true,
|
|
84
98
|
signal: AbortSignal.timeout(timeoutMs),
|
|
85
|
-
}
|
|
99
|
+
}
|
|
100
|
+
if (this.dispatcher) fetchOpts.dispatcher = this.dispatcher
|
|
101
|
+
const res = await fetch(`${this.apiRoot}/bot${this.token}/${method}`, fetchOpts)
|
|
86
102
|
const json = await res.json().catch(() => ({}))
|
|
87
103
|
if (!res.ok || json.ok === false) throw new Error(`telegram ${method}: ${json.description || res.status}`)
|
|
88
104
|
return json.result
|
|
@@ -110,10 +126,12 @@ export class TelegramAdapter {
|
|
|
110
126
|
|
|
111
127
|
async downloadFile(filePath) {
|
|
112
128
|
const timeoutMs = (this.timeoutSeconds * 1000) + 30000
|
|
113
|
-
const
|
|
129
|
+
const fetchOpts = {
|
|
114
130
|
keepalive: true,
|
|
115
131
|
signal: AbortSignal.timeout(timeoutMs),
|
|
116
|
-
}
|
|
132
|
+
}
|
|
133
|
+
if (this.dispatcher) fetchOpts.dispatcher = this.dispatcher
|
|
134
|
+
const res = await fetch(`${this.apiRoot}/file/bot${this.token}/${filePath}`, fetchOpts)
|
|
117
135
|
if (!res.ok) throw new Error(`telegram download HTTP ${res.status}`)
|
|
118
136
|
return new Uint8Array(await res.arrayBuffer())
|
|
119
137
|
}
|
|
@@ -204,6 +222,13 @@ export class TelegramAdapter {
|
|
|
204
222
|
if (this.statusIndicator) this.setStatusIndicator(this.statusOffline).catch((err) => {
|
|
205
223
|
this.logger?.debug?.('telegram setStatusIndicator offline failed:', err?.message || err)
|
|
206
224
|
})
|
|
225
|
+
if (this.ownDispatcher) {
|
|
226
|
+
try {
|
|
227
|
+
this.ownDispatcher.close?.().catch?.(() => {})
|
|
228
|
+
} catch (err) {
|
|
229
|
+
this.logger?.debug?.('telegram dispatcher close error:', err?.message || err)
|
|
230
|
+
}
|
|
231
|
+
}
|
|
207
232
|
}
|
|
208
233
|
|
|
209
234
|
schedulePoll(delayMs) {
|
package/lib/client.js
CHANGED
|
@@ -105,6 +105,10 @@ window.__ModuleLoader__.load({
|
|
|
105
105
|
webhookSecretHint: 'Leave empty to keep current configured secret',
|
|
106
106
|
webhookSecretConfigured: 'Secret set',
|
|
107
107
|
webhookSecretRequired: 'Secret required',
|
|
108
|
+
proxyUrl: 'Proxy URL (HTTP, HTTPS, SOCKS5)',
|
|
109
|
+
proxyUrlHint: 'Optional proxy for Telegram API requests (e.g. socks5://127.0.0.1:1080 or http://127.0.0.1:8080).',
|
|
110
|
+
apiRoot: 'Custom Telegram Bot API Base URL',
|
|
111
|
+
apiRootHint: 'Custom API root for reverse proxies or local Bot API servers. Default: https://api.telegram.org',
|
|
108
112
|
sessionScope: 'Group Session Scope',
|
|
109
113
|
sessionScopeChat: 'Shared per chat/topic',
|
|
110
114
|
sessionScopeUser: 'Per-user session (recommended)',
|
|
@@ -248,6 +252,10 @@ window.__ModuleLoader__.load({
|
|
|
248
252
|
webhookSecretHint: '留空保持当前配置的密钥',
|
|
249
253
|
webhookSecretConfigured: '密钥已设置',
|
|
250
254
|
webhookSecretRequired: '必须设置密钥',
|
|
255
|
+
proxyUrl: '代理地址 (HTTP, HTTPS, SOCKS5)',
|
|
256
|
+
proxyUrlHint: 'Telegram API 请求的可选代理(例如 socks5://127.0.0.1:1080 或 http://127.0.0.1:8080)。',
|
|
257
|
+
apiRoot: '自定义 Telegram Bot API 地址',
|
|
258
|
+
apiRootHint: '用于反向代理或本地 Bot API 服务器的自定义根地址。默认:https://api.telegram.org',
|
|
251
259
|
sessionScope: '群组会话范围',
|
|
252
260
|
sessionScopeChat: '每个聊天/话题共享',
|
|
253
261
|
sessionScopeUser: '每用户独立会话 (推荐)',
|
|
@@ -510,6 +518,8 @@ window.__ModuleLoader__.load({
|
|
|
510
518
|
alerts: t.alerts || { enabled: false, chatId: '', threadId: 0, home: '', events: ['error', 'pairing'] },
|
|
511
519
|
botToken: t.botToken || '',
|
|
512
520
|
webhookSecret: t.webhookSecret || '',
|
|
521
|
+
proxyUrl: t.proxyUrl || '',
|
|
522
|
+
apiRoot: t.apiRoot || '',
|
|
513
523
|
},
|
|
514
524
|
discord: {
|
|
515
525
|
enabled: d.enabled === true,
|
|
@@ -1467,6 +1477,22 @@ window.__ModuleLoader__.load({
|
|
|
1467
1477
|
onChange: (e) => setWebhookSecret(e.target.value),
|
|
1468
1478
|
})
|
|
1469
1479
|
),
|
|
1480
|
+
React.createElement(Field, { label: t('proxyUrl'), hint: t('proxyUrlHint') },
|
|
1481
|
+
React.createElement('input', {
|
|
1482
|
+
className: 'msgw-input',
|
|
1483
|
+
value: cfg.telegram?.proxyUrl || '',
|
|
1484
|
+
placeholder: 'socks5://127.0.0.1:1080 or http://127.0.0.1:8080',
|
|
1485
|
+
onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, proxyUrl: e.target.value } }),
|
|
1486
|
+
})
|
|
1487
|
+
),
|
|
1488
|
+
React.createElement(Field, { label: t('apiRoot'), hint: t('apiRootHint') },
|
|
1489
|
+
React.createElement('input', {
|
|
1490
|
+
className: 'msgw-input',
|
|
1491
|
+
value: cfg.telegram?.apiRoot || '',
|
|
1492
|
+
placeholder: 'https://api.telegram.org',
|
|
1493
|
+
onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, apiRoot: e.target.value } }),
|
|
1494
|
+
})
|
|
1495
|
+
),
|
|
1470
1496
|
React.createElement(Field, { label: t('pollTimeout') },
|
|
1471
1497
|
React.createElement('input', {
|
|
1472
1498
|
type: 'number',
|
package/lib/config.js
CHANGED
|
@@ -39,6 +39,8 @@ export const PluginConfig = z.object({
|
|
|
39
39
|
webhookUrl: z.string().default(''),
|
|
40
40
|
webhookSecret: z.string().role('secret').default(''),
|
|
41
41
|
webhookPath: z.string().default('/dsh-messenger-gateway/telegram/webhook'),
|
|
42
|
+
proxyUrl: z.string().default('').description('Proxy URL for Telegram API requests (e.g. socks5://127.0.0.1:1080, http://127.0.0.1:8080)'),
|
|
43
|
+
apiRoot: z.string().default('').description('Custom Telegram Bot API root URL (default: https://api.telegram.org)'),
|
|
42
44
|
voiceMode: z.union([z.const('mirror'), z.const('always'), z.const('off')]).default('mirror')
|
|
43
45
|
.description('mirror: TTS when inbound was voice; always/off override (per-user /voice wins)'),
|
|
44
46
|
quickActions: z.boolean().default(false).description('Show quick actions keyboard in Telegram (/new, /stop, /voice, /status)'),
|
package/lib/file-manager.js
CHANGED
|
@@ -76,6 +76,15 @@ export function resolveSafePath(baseCwd, userPath = '.') {
|
|
|
76
76
|
return { base, target, relativePath: rel || '.' }
|
|
77
77
|
}
|
|
78
78
|
|
|
79
|
+
/**
|
|
80
|
+
* Resolves candidate path strictly inside base directory (Issue #127).
|
|
81
|
+
* Throws ERR_PATH_TRAVERSAL if candidate escapes base (lexically, absolute, drive letter or symlink).
|
|
82
|
+
* Returns the resolved absolute target path.
|
|
83
|
+
*/
|
|
84
|
+
export function resolveInside(base, candidate = '.') {
|
|
85
|
+
return resolveSafePath(base, candidate).target
|
|
86
|
+
}
|
|
87
|
+
|
|
79
88
|
export async function listFiles(baseCwd, subPath = '.', opts = {}) {
|
|
80
89
|
const { maxEntries = 50, showHidden = false } = opts
|
|
81
90
|
const { base, target, relativePath } = resolveSafePath(baseCwd, subPath)
|
package/lib/gateway.js
CHANGED
|
@@ -207,13 +207,13 @@ export class Gateway {
|
|
|
207
207
|
collector.onStream?.(collector.streamText, collector.toolName)
|
|
208
208
|
}
|
|
209
209
|
} else if (event.type === 'tool/call') {
|
|
210
|
-
collector.toolName = extractToolName(event.data) || collector.toolName
|
|
210
|
+
collector.toolName = extractToolName(event.data || event) || collector.toolName
|
|
211
211
|
collector.onStream?.(collector.streamText || '', collector.toolName)
|
|
212
212
|
} else if (event.type === 'tool/result') {
|
|
213
213
|
collector.toolName = ''
|
|
214
214
|
collector.onStream?.(collector.streamText || '', '')
|
|
215
215
|
} else if (event.type === 'turn/end') {
|
|
216
|
-
collector.reason = event.data?.reason || event.data
|
|
216
|
+
collector.reason = event.data?.reason || event.reason || event.data
|
|
217
217
|
}
|
|
218
218
|
}
|
|
219
219
|
|
|
@@ -225,6 +225,8 @@ export class Gateway {
|
|
|
225
225
|
this.ctx.on('turn/start', (session, data) => onHost(session, { type: 'turn/start', data })),
|
|
226
226
|
this.ctx.on('assistant/message', (session, message) => onHost(session, { type: 'assistant/message', data: { message } })),
|
|
227
227
|
this.ctx.on('assistant/chunk', (session, chunk) => onHost(session, { type: 'assistant/chunk', data: { chunk } })),
|
|
228
|
+
this.ctx.on('tool/call', (session, data) => onHost(session, { type: 'tool/call', data })),
|
|
229
|
+
this.ctx.on('tool/result', (session, data) => onHost(session, { type: 'tool/result', data })),
|
|
228
230
|
]
|
|
229
231
|
this.disposeListener = () => {
|
|
230
232
|
for (const un of unsubs) {
|
package/lib/index.js
CHANGED
|
@@ -58,6 +58,8 @@ function publicConfig(cfg, gw, ctx) {
|
|
|
58
58
|
webhookPath: cfg.telegram.webhookPath,
|
|
59
59
|
webhookSecretConfigured: Boolean(String(cfg.telegram.webhookSecret || '').trim()),
|
|
60
60
|
botTokenConfigured: Boolean(String(cfg.telegram.botToken || '').trim()),
|
|
61
|
+
proxyUrl: cfg.telegram.proxyUrl || '',
|
|
62
|
+
apiRoot: cfg.telegram.apiRoot || '',
|
|
61
63
|
voiceMode: cfg.telegram.voiceMode,
|
|
62
64
|
quickActions: cfg.telegram.quickActions !== false,
|
|
63
65
|
artifactPreviews: cfg.telegram.artifactPreviews !== false,
|
|
@@ -343,13 +345,18 @@ export function apply(ctx, config) {
|
|
|
343
345
|
const gw = getGw()
|
|
344
346
|
if (gw) gw.syncTelegramCommands().catch((err) => ctx.logger?.debug?.(`sync telegram commands on skills change: ${err?.message || err}`))
|
|
345
347
|
}
|
|
346
|
-
const
|
|
347
|
-
|
|
348
|
-
|
|
348
|
+
const unbinds = [
|
|
349
|
+
ctx.on('tools/change', onSkillsChange),
|
|
350
|
+
ctx.on('tools/update', onSkillsChange),
|
|
351
|
+
ctx.on('tools/updated', onSkillsChange),
|
|
352
|
+
ctx.on('skills/change', onSkillsChange),
|
|
353
|
+
ctx.on('skills/updated', onSkillsChange),
|
|
354
|
+
ctx.on('skills/update', onSkillsChange),
|
|
355
|
+
]
|
|
349
356
|
return () => {
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
357
|
+
for (const un of unbinds) {
|
|
358
|
+
if (typeof un === 'function') un()
|
|
359
|
+
}
|
|
353
360
|
}
|
|
354
361
|
}, 'dsh-messenger-gateway: dynamic skills sync')
|
|
355
362
|
|
|
@@ -372,7 +379,7 @@ export function apply(ctx, config) {
|
|
|
372
379
|
if (event.type !== 'turn/end') return
|
|
373
380
|
const prefixes = cfg.excludeSessionPrefixes || ['msgw-']
|
|
374
381
|
if (isExcludedSession(session.id, prefixes)) return
|
|
375
|
-
const reason = event.data?.reason
|
|
382
|
+
const reason = event.data?.reason || event.reason || event.data
|
|
376
383
|
const kind = reason?.kind === 'completed' ? 'task_done' : 'error'
|
|
377
384
|
const events = new Set(cfg.events?.length ? cfg.events : ['task_done', 'error'])
|
|
378
385
|
if (!events.has(kind)) return
|
package/lib/proxy.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'
|
|
2
|
+
|
|
3
|
+
const require = createRequire(import.meta.url)
|
|
4
|
+
|
|
5
|
+
const ALLOWED_PROTOCOLS = new Set(['http:', 'https:', 'socks5:', 'socks5h:', 'socks:'])
|
|
6
|
+
|
|
7
|
+
export function normalizeProxyUrl(rawUrl) {
|
|
8
|
+
const trimmed = String(rawUrl || '').trim()
|
|
9
|
+
if (!trimmed) return ''
|
|
10
|
+
let parsed
|
|
11
|
+
try {
|
|
12
|
+
parsed = new URL(trimmed)
|
|
13
|
+
} catch (err) {
|
|
14
|
+
throw new Error(`Invalid proxy URL "${trimmed}": ${err.message}`)
|
|
15
|
+
}
|
|
16
|
+
if (!ALLOWED_PROTOCOLS.has(parsed.protocol)) {
|
|
17
|
+
throw new Error(`Unsupported proxy protocol "${parsed.protocol}". Supported protocols: http, https, socks5, socks5h`)
|
|
18
|
+
}
|
|
19
|
+
return parsed.toString()
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function normalizeApiRoot(rawUrl) {
|
|
23
|
+
const trimmed = String(rawUrl || '').trim()
|
|
24
|
+
if (!trimmed) return 'https://api.telegram.org'
|
|
25
|
+
let parsed
|
|
26
|
+
try {
|
|
27
|
+
parsed = new URL(trimmed)
|
|
28
|
+
} catch (err) {
|
|
29
|
+
throw new Error(`Invalid apiRoot URL "${trimmed}": ${err.message}`)
|
|
30
|
+
}
|
|
31
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
32
|
+
throw new Error(`Unsupported apiRoot protocol "${parsed.protocol}". Must be http: or https:`)
|
|
33
|
+
}
|
|
34
|
+
return trimmed.replace(/\/+$/, '')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function createTelegramDispatcher(proxyUrl, options = {}) {
|
|
38
|
+
const normalized = normalizeProxyUrl(proxyUrl)
|
|
39
|
+
if (!normalized) return null
|
|
40
|
+
|
|
41
|
+
let undici
|
|
42
|
+
try {
|
|
43
|
+
undici = require('undici')
|
|
44
|
+
} catch (err) {
|
|
45
|
+
throw new Error(`Cannot configure proxy: "undici" module is not available in runtime environment (${err.message})`)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const ProxyAgent = undici.ProxyAgent
|
|
49
|
+
if (typeof ProxyAgent !== 'function') {
|
|
50
|
+
throw new Error('Cannot configure proxy: "undici.ProxyAgent" is not available')
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
const agent = new ProxyAgent({
|
|
55
|
+
uri: normalized,
|
|
56
|
+
...(options.agentOptions || {}),
|
|
57
|
+
})
|
|
58
|
+
options.logger?.info?.(`dsh-messenger-gateway: configured Telegram proxy dispatcher via ${new URL(normalized).protocol}//${new URL(normalized).host}`)
|
|
59
|
+
return agent
|
|
60
|
+
} catch (err) {
|
|
61
|
+
throw new Error(`Failed to create proxy dispatcher for "${normalized}": ${err.message}`)
|
|
62
|
+
}
|
|
63
|
+
}
|
package/lib/stream.js
CHANGED
|
@@ -11,7 +11,8 @@ export function extractTextDelta(chunk) {
|
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
export function extractToolName(eventData) {
|
|
14
|
-
|
|
14
|
+
if (typeof eventData === 'string') return eventData
|
|
15
|
+
const name = eventData?.tool?.name || eventData?.toolName || eventData?.name || eventData?.tool
|
|
15
16
|
return name ? String(name) : ''
|
|
16
17
|
}
|
|
17
18
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodandready/dsh-messenger-gateway",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.16",
|
|
4
4
|
"description": "Telegram messenger bridge for DeepSeek Harness: sessions, steer, homes, inline asks, notify bridge, and optional TTS voice notes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|