dsh-message-gateway 0.1.0
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/LICENSE +21 -0
- package/README.en.md +74 -0
- package/README.es.md +74 -0
- package/README.md +77 -0
- package/cordis.patch.yml +5 -0
- package/docs/architecture.md +131 -0
- package/docs/webhooks.md +81 -0
- package/docs/wechaty-gateway.md +66 -0
- package/lib/client.js +660 -0
- package/lib/client.js.map +7 -0
- package/lib/index.js +2768 -0
- package/lib/index.js.map +7 -0
- package/package.json +99 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dsh-message-gateway contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.en.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# dsh-message-gateway
|
|
2
|
+
|
|
3
|
+
[中文](README.md) · [Español](README.es.md)
|
|
4
|
+
|
|
5
|
+
A message-platform gateway plugin for the DSH Web GUI: a "Message platforms" entry below the "New session" button opens a full-screen manager for multi-platform message connectors — credential save, connection tests, status monitoring — plus a built-in persistent bridge for the WeCom AI bot: external messages drive the DSH assistant through a dedicated agent session, and replies stream back token by token.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Sidebar entry**: a "📮 Message platforms" button below "New session" opens the full-screen manager (close with ESC or by clicking the backdrop)
|
|
10
|
+
- **Multi-platform connectors**: Telegram / Discord / QQ bot / WeCom / WeCom AI bot / WeChat (external Wechaty gateway) / WeChat Official Account / WhatsApp / Email / Webhooks
|
|
11
|
+
- **Telegram bot**: save a Bot Token to enable long polling instantly; chat with the bot directly (streaming replies via send + progressive edit, same as web)
|
|
12
|
+
- **Discord bot**: save a Bot Token to connect to the gateway (enable the MESSAGE CONTENT privileged intent in the developer portal); chat in channels or DMs
|
|
13
|
+
- **QQ bot**: save appId + secret to connect to the open-platform gateway (channels/groups/DMs); passive replies + streaming edits
|
|
14
|
+
- **WeCom app**: fill in CorpID/AgentID/Secret plus the callback Token/EncodingAESKey, configure the callback URL (`/gateway/wecom/callback`) in the admin console, and users who message the app get auto replies
|
|
15
|
+
- **WeChat Official Account**: fill in AppID/Secret plus the callback Token, configure the server URL (`/gateway/wechat-mp/callback`) in the console, and followers who message get auto replies
|
|
16
|
+
- **WhatsApp**: fill in Token + Phone Number ID, configure the webhook (`/gateway/whatsapp/webhook`) in the Meta console, and users who message get auto replies
|
|
17
|
+
- **Email**: fill in IMAP (receiving, 993/143) + SMTP (replying, 465/587/25); messages are grouped into per-thread sessions and replies use Re: original subject
|
|
18
|
+
- **Credential management**: plaintext is persisted only to `~/.dsh/gateway.json` (mode 600, atomic write); `/gateway/list` never returns credential plaintext, only a `configured` flag
|
|
19
|
+
- **Connection tests**: real per-platform checks — Telegram/Discord via Bot API, QQ via access_token, WeCom via gettoken, WeChat MP via cgi-bin/token, WhatsApp via Graph API, Email via IMAP TCP banner, WeCom AI bot via the official SDK long connection (authenticated = pass)
|
|
20
|
+
- **WeCom AI bot persistent bridge**: official SDK WebSocket long connection with exponential backoff reconnect; incoming text messages are injected into an isolated dedicated agent session that wakes the DSH driver; replies stream back as chunks and finalize via `response_url`
|
|
21
|
+
- **Group-chat @mention stripping**: the leading `@bot-name` is removed before the assistant sees the message
|
|
22
|
+
- **Slash commands**: `/help` / `/time` / `/status` (Chinese aliases: 帮助/菜单/时间/状态)
|
|
23
|
+
- **Enter-chat welcome**: a welcome message is auto-replied when a user enters a single chat for the first time that day
|
|
24
|
+
- **Proactive send channel**: `POST /gateway/send` (`{"chatid": "...", "content": "..."}`, single chat = userid, group chat = group id) sends markdown messages as the bot
|
|
25
|
+
- **Webhook receive endpoint**: `POST /gateway/webhook/in` accepts messages from external systems (any of `text` / `content` / `message`), injects them into the dedicated agent session and returns the full reply synchronously; an optional HMAC-SHA256 signing secret validates requests (contract: [docs/webhooks.md](docs/webhooks.md))
|
|
26
|
+
- **WeChat personal accounts (optional external gateway)**: QR login and status polling against a local Wechaty HTTP gateway (contract: [docs/wechaty-gateway.md](docs/wechaty-gateway.md))
|
|
27
|
+
- **Multilingual**: Chinese / English / Español, following the DSH Web UI language (Spanish browsers auto-switch); defaults to Simplified Chinese
|
|
28
|
+
- Light / dark theme follows the DSH Web GUI
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
1. Open DSH Web (`dsh web`) and click the "Message platforms" button in the sidebar
|
|
33
|
+
2. Pick a platform on the left, fill in credentials on the right
|
|
34
|
+
3. Click **Save**: credentials are persisted and a connection test runs automatically, refreshing the status immediately
|
|
35
|
+
4. Click **Test connection**: tests the current form values without saving
|
|
36
|
+
5. Saving `botId + secret` for the WeCom AI bot establishes the persistent bridge right away; deleting the config disconnects it
|
|
37
|
+
|
|
38
|
+
## Install
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
# From npm (generic plugin, usable by any DSH user)
|
|
42
|
+
dsh plugin --profile web add dsh-message-gateway
|
|
43
|
+
|
|
44
|
+
# Or link for local development
|
|
45
|
+
dsh plugin --profile web add link:/path/to/dsh-message-gateway
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Restart `dsh web` — the "Message platforms" button appears below "New session" in the sidebar. Open the page, pick a platform, fill in credentials and click **Save** — for the WeCom AI bot, saving `botId + secret` establishes the persistent bridge immediately and you can chat with the bot in WeCom right away (same as web: per-chat sessions + automatic context compression).
|
|
49
|
+
|
|
50
|
+
## Config
|
|
51
|
+
|
|
52
|
+
All options have defaults and the plugin works out of the box; tune them via `dsh plugin config` or the profile config file:
|
|
53
|
+
|
|
54
|
+
| Option | Type | Default | Description |
|
|
55
|
+
| --- | --- | --- | --- |
|
|
56
|
+
| `botLocale` | `zh` \| `en` | `zh` | Bot reply language |
|
|
57
|
+
| `maxChatAgents` | number | `40` | Max chat sessions kept per bot; oldest is evicted beyond this |
|
|
58
|
+
| `autoStartWecom` | boolean | `true` | Auto-connect the WeCom AI bot from saved credentials at startup |
|
|
59
|
+
| `groupReply` | boolean | `true` | Reply to group messages (false = single chats only) |
|
|
60
|
+
|
|
61
|
+
## Docs
|
|
62
|
+
|
|
63
|
+
- [Architecture & extension guide](docs/architecture.md) (how to add a platform connector)
|
|
64
|
+
- [Webhook receive endpoint contract](docs/webhooks.md)
|
|
65
|
+
- [WeChat (Wechaty) HTTP gateway contract](docs/wechaty-gateway.md)
|
|
66
|
+
|
|
67
|
+
## Architecture
|
|
68
|
+
|
|
69
|
+
- **Host half** (`lib/index.js`): `/gateway/*` routes (list / save / delete / test / wechat-status) + `BridgeManager` (agent session injection and event-stream polling) + `WecomBridge` (SDK long-connection lifecycle) + `gateway-store` (credential persistence)
|
|
70
|
+
- **Client half** (`lib/client.js`): sidebar button mount + full-screen platform manager (React, loaded via the `__ModuleLoader__` closure)
|
|
71
|
+
|
|
72
|
+
## License
|
|
73
|
+
|
|
74
|
+
MIT
|
package/README.es.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# dsh-message-gateway
|
|
2
|
+
|
|
3
|
+
[中文](README.md) · [English](README.en.md)
|
|
4
|
+
|
|
5
|
+
Un plugin de pasarela de mensajería para la GUI web de DSH: una entrada "Plataformas de mensajería" debajo del botón "Nueva sesión" abre un gestor a pantalla completa para conectores de mensajería multiplataforma — guardado de credenciales, pruebas de conexión, monitoreo de estado — más un puente persistente integrado para el bot de IA de WeCom: los mensajes externos impulsan al asistente de DSH a través de una sesión de agente dedicada, y las respuestas se transmiten token a token.
|
|
6
|
+
|
|
7
|
+
## Características
|
|
8
|
+
|
|
9
|
+
- **Entrada en la barra lateral**: un botón "📮 Plataformas de mensajería" debajo de "Nueva sesión" abre el gestor a pantalla completa (cierre con ESC o haciendo clic en el fondo)
|
|
10
|
+
- **Conectores multiplataforma**: Telegram / Discord / Bot de QQ / WeCom / Bot de IA de WeCom / WeChat (pasarela Wechaty externa) / Cuenta oficial de WeChat / WhatsApp / Email / Webhooks
|
|
11
|
+
- **Bot de Telegram**: guarde un Bot Token para activar el sondeo largo al instante; chatee directamente con el bot (respuestas en streaming mediante envío + edición progresiva, igual que en la web)
|
|
12
|
+
- **Bot de Discord**: guarde un Bot Token para conectarse a la pasarela (habilite la intención privilegiada MESSAGE CONTENT en el portal de desarrolladores); chatee en canales o mensajes directos
|
|
13
|
+
- **Bot de QQ**: guarde appId + secret para conectarse a la pasarela de la plataforma abierta (canales/grupos/DM); respuestas pasivas + edición en streaming
|
|
14
|
+
- **App de WeCom**: rellene CorpID/AgentID/Secret más el Token/EncodingAESKey de callback, configure la URL de callback (`/gateway/wecom/callback`) en la consola, y los usuarios que escriban al app reciben respuestas automáticas
|
|
15
|
+
- **Cuenta oficial de WeChat**: rellene AppID/Secret más el Token de callback, configure la URL del servidor (`/gateway/wechat-mp/callback`) en la consola, y los seguidores que escriban reciben respuestas automáticas
|
|
16
|
+
- **WhatsApp**: rellene Token + Phone Number ID, configure el webhook (`/gateway/whatsapp/webhook`) en la consola de Meta, y los usuarios que escriban reciben respuestas automáticas
|
|
17
|
+
- **Email**: rellene IMAP (recepción, 993/143) + SMTP (respuesta, 465/587/25); los mensajes se agrupan en sesiones por hilo y las respuestas usan Re: asunto original
|
|
18
|
+
- **Gestión de credenciales**: el texto plano se guarda solo en `~/.dsh/gateway.json` (modo 600, escritura atómica); `/gateway/list` nunca devuelve credenciales, solo un marcador `configured`
|
|
19
|
+
- **Pruebas de conexión**: comprobaciones reales por plataforma — Telegram/Discord vía Bot API, QQ vía access_token, WeCom vía gettoken, cuenta oficial vía cgi-bin/token, WhatsApp vía Graph API, Email vía banner TCP de IMAP, Bot de IA de WeCom vía la conexión larga del SDK oficial (autenticado = correcto)
|
|
20
|
+
- **Puente persistente del Bot de IA de WeCom**: conexión larga WebSocket del SDK oficial con reconexión por retroceso exponencial; los mensajes de texto entrantes se inyectan en una sesión de agente dedicada y aislada que despierta al controlador de DSH; las respuestas se transmiten como fragmentos y finalizan vía `response_url`
|
|
21
|
+
- **Eliminación de menciones @ en grupos**: se quita el `@nombre-del-bot` inicial antes de que el asistente vea el mensaje
|
|
22
|
+
- **Comandos de barra**: `/help` / `/time` / `/status` (alias en chino: 帮助/菜单/时间/状态)
|
|
23
|
+
- **Mensaje de bienvenida**: se responde automáticamente un saludo cuando un usuario entra a un chat individual por primera vez ese día
|
|
24
|
+
- **Canal de envío proactivo**: `POST /gateway/send` (`{"chatid": "...", "content": "..."}`, chat individual = userid, grupo = id de grupo) envía mensajes markdown como el bot
|
|
25
|
+
- **Endpoint de recepción de webhooks**: `POST /gateway/webhook/in` acepta mensajes de sistemas externos (cualquiera de `text` / `content` / `message`), los inyecta en la sesión de agente dedicada y devuelve la respuesta completa de forma síncrona; un secreto de firma HMAC-SHA256 opcional valida las peticiones (contrato: [docs/webhooks.md](docs/webhooks.md))
|
|
26
|
+
- **Cuentas personales de WeChat (pasarela externa opcional)**: inicio de sesión por QR y sondeo de estado contra una pasarela HTTP Wechaty local (contrato: [docs/wechaty-gateway.md](docs/wechaty-gateway.md))
|
|
27
|
+
- **Multilingüe**: chino / inglés / español, siguiendo el idioma de la interfaz web de DSH (los navegadores en español cambian automáticamente); por defecto chino simplificado
|
|
28
|
+
- Tema claro / oscuro siguiendo la GUI web de DSH
|
|
29
|
+
|
|
30
|
+
## Uso
|
|
31
|
+
|
|
32
|
+
1. Abra DSH Web (`dsh web`) y haga clic en el botón "Plataformas de mensajería" de la barra lateral
|
|
33
|
+
2. Elija una plataforma a la izquierda y complete las credenciales a la derecha
|
|
34
|
+
3. Haga clic en **Guardar**: las credenciales se persisten y se ejecuta automáticamente una prueba de conexión, actualizando el estado al instante
|
|
35
|
+
4. Haga clic en **Probar conexión**: prueba los valores actuales del formulario sin guardarlos
|
|
36
|
+
5. Guardar `botId + secret` del Bot de IA de WeCom establece el puente persistente de inmediato; eliminar la configuración lo desconecta
|
|
37
|
+
|
|
38
|
+
## Instalación
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
# Desde npm (plugin genérico, utilizable por cualquier usuario de DSH)
|
|
42
|
+
dsh plugin --profile web add dsh-message-gateway
|
|
43
|
+
|
|
44
|
+
# O enlazado para desarrollo local
|
|
45
|
+
dsh plugin --profile web add link:/ruta/a/dsh-message-gateway
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Reinicie `dsh web`: el botón "Plataformas de mensajería" aparece debajo de "Nueva sesión" en la barra lateral. Abra la página, elija una plataforma, complete las credenciales y haga clic en **Guardar** — para el Bot de IA de WeCom, guardar `botId + secret` establece el puente persistente de inmediato y puede chatear con el bot en WeCom al momento (igual que en la web: sesiones por chat + compresión automática de contexto).
|
|
49
|
+
|
|
50
|
+
## Configuración
|
|
51
|
+
|
|
52
|
+
Todas las opciones tienen valores por defecto y el plugin funciona de inmediato; ajústelas vía `dsh plugin config` o el archivo de configuración del perfil:
|
|
53
|
+
|
|
54
|
+
| Opción | Tipo | Por defecto | Descripción |
|
|
55
|
+
| --- | --- | --- | --- |
|
|
56
|
+
| `botLocale` | `zh` \| `en` | `zh` | Idioma de las respuestas del bot |
|
|
57
|
+
| `maxChatAgents` | number | `40` | Máximo de sesiones de chat por bot; se elimina la más antigua al superarlo |
|
|
58
|
+
| `autoStartWecom` | boolean | `true` | Conectar automáticamente el Bot de IA de WeCom con las credenciales guardadas al iniciar |
|
|
59
|
+
| `groupReply` | boolean | `true` | Responder mensajes de grupo (false = solo chats individuales) |
|
|
60
|
+
|
|
61
|
+
## Documentación
|
|
62
|
+
|
|
63
|
+
- [Arquitectura y guía de extensión](docs/architecture.md) (cómo añadir un conector de plataforma)
|
|
64
|
+
- [Contrato del endpoint de recepción de webhooks](docs/webhooks.md)
|
|
65
|
+
- [Contrato de la pasarela HTTP de WeChat (Wechaty)](docs/wechaty-gateway.md)
|
|
66
|
+
|
|
67
|
+
## Arquitectura
|
|
68
|
+
|
|
69
|
+
- **Mitad host** (`lib/index.js`): rutas `/gateway/*` (list / save / delete / test / wechat-status) + `BridgeManager` (inyección de sesión de agente y sondeo del flujo de eventos) + `WecomBridge` (ciclo de vida de la conexión larga del SDK) + `gateway-store` (persistencia de credenciales)
|
|
70
|
+
- **Mitad cliente** (`lib/client.js`): montaje del botón de la barra lateral + gestor a pantalla completa (React, cargado vía el cierre de `__ModuleLoader__`)
|
|
71
|
+
|
|
72
|
+
## Licencia
|
|
73
|
+
|
|
74
|
+
MIT
|
package/README.md
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# dsh-message-gateway
|
|
2
|
+
|
|
3
|
+
[English](README.en.md) · [Español](README.es.md)
|
|
4
|
+
|
|
5
|
+
DSH Web GUI 的消息平台网关插件:在侧边栏「新会话」按钮下方提供「消息平台」入口,全屏管理多平台消息连接器——凭据保存、连接测试、状态监控,并内置企业微信智能机器人的常驻桥接:外部消息经专用 agent 会话驱动 DSH 助手,回复按 token 流式回发。
|
|
6
|
+
|
|
7
|
+
## 功能
|
|
8
|
+
|
|
9
|
+
- **侧边栏入口**:「新会话」按钮下方新增「📮 消息平台」按钮,点击打开全屏管理页(ESC / 点击遮罩关闭)
|
|
10
|
+
- **多平台连接器**:Telegram / Discord / QQ 机器人 / 企业微信 / 企业微信智能机器人 / 微信(外部 Wechaty 网关)/ 微信公众号 / WhatsApp / Email / Webhooks
|
|
11
|
+
- **Telegram 机器人**:填 Bot Token 保存即启用长轮询,与机器人对话即可使用(流式回复:发送后渐进编辑,与 Web 一致)
|
|
12
|
+
- **Discord 机器人**:填 Bot Token 保存即接入网关(需在开发者后台开启 MESSAGE CONTENT 意图),频道/私信直接对话
|
|
13
|
+
- **QQ 机器人**:填 appId + secret 保存即连接开放平台网关(频道/群/私信),被动回复 + 流式编辑
|
|
14
|
+
- **企业微信应用**:填 CorpID/AgentID/Secret + 回调 Token/EncodingAESKey,后台配置回调 URL(`/gateway/wecom/callback`)后发消息即自动对话
|
|
15
|
+
- **微信公众号**:填 AppID/Secret + 回调 Token,后台配置服务器 URL(`/gateway/wechat-mp/callback`)后发消息即自动对话
|
|
16
|
+
- **WhatsApp**:填 Token + Phone Number ID,Meta 后台配置 Webhook(`/gateway/whatsapp/webhook`)后发消息即自动对话
|
|
17
|
+
- **Email**:填 IMAP(收件,993/143)+ SMTP(回复,465/587/25),按邮件线程自动归类会话,回复用 Re: 原主题
|
|
18
|
+
- **凭据管理**:明文只落盘 `~/.dsh/gateway.json`(权限 600,原子写入),`/gateway/list` 永不回传凭据明文,只返回 configured 标记
|
|
19
|
+
- **连接测试**:每个平台独立的真实连接测试——Telegram/Discord 走 Bot API、QQ 走 access_token、企微走 gettoken、微信公众号走 cgi-bin/token、WhatsApp 走 Graph API、Email 走 IMAP TCP banner、企微智能机器人走官方 SDK 长连接(认证成功即通过)
|
|
20
|
+
- **企业微信智能机器人常驻桥**:官方 SDK WebSocket 长连接,断线自动指数退避重连;收到文本消息 → 注入隔离的专用 agent 会话唤醒 DSH 驱动 → 回复按 chunk 流式回发,结束时经 response_url 定稿
|
|
21
|
+
- **群聊 @提及剥离**:去掉开头的 @机器人名后交给助手
|
|
22
|
+
- **斜杠命令**:`/help` / `/time` / `/status`(含中文别名:帮助/菜单/时间/状态)
|
|
23
|
+
- **进入会话欢迎语**:用户当天首次进入单聊时自动回复欢迎消息
|
|
24
|
+
- **主动发送通道**:`POST /gateway/send`(`{"chatid": "...", "content": "..."}`,单聊=userid,群聊=群 ID)以机器人身份主动发送 markdown 消息
|
|
25
|
+
- **Webhook 接收端点**:`POST /gateway/webhook/in` 接收外部系统消息(`text` / `content` / `message` 任一字段),注入专用 agent 会话并同步返回完整回复;可配置 HMAC-SHA256 签名密钥校验(契约见 [docs/webhooks.md](docs/webhooks.md))
|
|
26
|
+
- **微信个人号(可选外部网关)**:对接本机 Wechaty HTTP 网关的扫码登录与状态轮询(契约见 [docs/wechaty-gateway.md](docs/wechaty-gateway.md))
|
|
27
|
+
- **多语言**:中文 / English / Español,自动跟随 DSH Web 界面语言(西班牙语浏览器自动切换),默认简体中文
|
|
28
|
+
- 明暗主题跟随 DSH Web GUI
|
|
29
|
+
|
|
30
|
+
## 使用
|
|
31
|
+
|
|
32
|
+
1. 打开 DSH Web(`dsh web`),点击侧边栏「消息平台」按钮
|
|
33
|
+
2. 左侧选择平台,右侧填写凭据
|
|
34
|
+
3. 点击「保存」:凭据落盘并立即自动触发一次连接测试,状态即时刷新
|
|
35
|
+
4. 点击「测试连接」:用当前表单值只测不存
|
|
36
|
+
5. 企微智能机器人保存 `botId + secret` 后立即建立常驻连接;删除配置即断开
|
|
37
|
+
|
|
38
|
+
## 安装
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
# 从 npm 安装(通用插件,任何 DSH 用户可直接使用)
|
|
42
|
+
dsh plugin --profile web add dsh-message-gateway
|
|
43
|
+
|
|
44
|
+
# 或本地开发以链接方式安装
|
|
45
|
+
dsh plugin --profile web add link:/path/to/dsh-message-gateway
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
重启 `dsh web`,侧边栏「新会话」按钮下方即出现「消息平台」按钮。打开页面,选择平台、
|
|
49
|
+
填入凭据并「保存」——企业微信智能机器人填 `botId + secret` 后立即建立常驻连接,即可
|
|
50
|
+
直接在企微里和机器人对话(与 Web 对话一致:每聊天独立会话 + 上下文自动压缩)。
|
|
51
|
+
|
|
52
|
+
## 配置
|
|
53
|
+
|
|
54
|
+
插件可通过 `dsh plugin config` 或 profile 配置文件调整(所有项均有默认值,开箱即用):
|
|
55
|
+
|
|
56
|
+
| 配置 | 类型 | 默认 | 说明 |
|
|
57
|
+
| --- | --- | --- | --- |
|
|
58
|
+
| `botLocale` | `zh` \| `en` | `zh` | 机器人回复文案语言 |
|
|
59
|
+
| `maxChatAgents` | number | `40` | 每机器人最多保留的聊天会话数,超出自动淘汰最旧 |
|
|
60
|
+
| `botModel` | `{provider, model}` | 无 | 可选:机器人专用模型(优先于部署默认模型;不填则与 Web 对话一致) |
|
|
61
|
+
| `autoStartWecom` | boolean | `true` | 启动时自动用已保存的企业微信智能机器人凭据连接 |
|
|
62
|
+
| `groupReply` | boolean | `true` | 是否回复群聊消息(false 时只处理单聊) |
|
|
63
|
+
|
|
64
|
+
## 文档
|
|
65
|
+
|
|
66
|
+
- [架构与扩展指南](docs/architecture.md)(如何新增平台连接器)
|
|
67
|
+
- [Webhook 接收端点契约](docs/webhooks.md)
|
|
68
|
+
- [微信(Wechaty)HTTP 网关契约](docs/wechaty-gateway.md)
|
|
69
|
+
|
|
70
|
+
## 架构
|
|
71
|
+
|
|
72
|
+
- **host 半区**(`lib/index.js`):`/gateway/*` 路由(list / save / delete / test / wechat-status)+ `BridgeManager`(agent 会话注入与事件流轮询)+ `WecomBridge`(SDK 长连接生命周期)+ `gateway-store`(凭据存储)
|
|
73
|
+
- **client 半区**(`lib/client.js`):侧边栏按钮挂载 + 全屏平台管理页(React,经 `__ModuleLoader__` 闭包加载)
|
|
74
|
+
|
|
75
|
+
## License
|
|
76
|
+
|
|
77
|
+
MIT
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# dsh-message-gateway 架构与扩展指南
|
|
2
|
+
|
|
3
|
+
本插件是一个**通用 DSH 消息平台网关**:任何 DSH 用户安装后即可使用——在侧边栏
|
|
4
|
+
「消息平台」页面填入各平台凭据,即可保存凭据、测试连接、查看状态;其中
|
|
5
|
+
**企业微信智能机器人**(`wecom-aibot`)与 **Webhooks** 提供真实的消息收发能力,
|
|
6
|
+
其余平台(Telegram / Discord / QQ / 企业微信 / 微信 / 微信公众号 / WhatsApp / Email)
|
|
7
|
+
当前提供凭据管理与连接测试,可作为后续常驻连接的接入点。
|
|
8
|
+
|
|
9
|
+
## 模块结构
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
src/
|
|
13
|
+
├── index.ts # 插件入口:Config schema、路由挂载、桥自启动
|
|
14
|
+
├── core/
|
|
15
|
+
│ ├── config.ts # 插件配置(schemastery,安装者可配置)
|
|
16
|
+
│ └── types.ts # host 与 client 共享的类型(平台定义/状态/测试结果)
|
|
17
|
+
├── host/
|
|
18
|
+
│ ├── gateway-store.ts # 凭据与状态存储 ~/.dsh/gateway.json(0600,原子写)
|
|
19
|
+
│ ├── platforms.ts # 平台定义表 + 各平台连接测试(Node fetch/net)
|
|
20
|
+
│ ├── routes.ts # /gateway/* 路由(list/save/delete/test/send/webhook)
|
|
21
|
+
│ ├── bridge-manager.ts # 常驻桥管理:每聊天独立 agent 会话 + 流式回发
|
|
22
|
+
│ ├── wecom-bridge.ts # 企业微信智能机器人 SDK 长连接生命周期
|
|
23
|
+
│ └── bot-i18n.ts # 机器人回复文案(zh/en,由配置 botLocale 决定)
|
|
24
|
+
└── client/ # 浏览器半区:侧边栏按钮 + 全屏管理页(React)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## 两半区
|
|
28
|
+
|
|
29
|
+
- **host 半区**(`lib/index.js`,Node):路由、存储、连接测试、常驻桥。所需服务
|
|
30
|
+
`webServer` / `sessions` / `agents`。
|
|
31
|
+
- **client 半区**(`lib/client.js`,浏览器):侧边栏「消息平台」按钮 + 全屏管理页,
|
|
32
|
+
经 `window.__ModuleLoader__` 闭包加载,三语(zh/en/es)。
|
|
33
|
+
|
|
34
|
+
## 数据流(企业微信智能机器人)
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
企业微信消息 → WS 长连接 (wecom-bridge)
|
|
38
|
+
→ 按 chatid/userid 路由(每聊天独立,自动新建会话)
|
|
39
|
+
→ 命令 (/help /time /status /new) 直接回复
|
|
40
|
+
→ 否则注入该聊天的独立 agent 会话 (agents.create,继承 root agent 配置)
|
|
41
|
+
→ agent 驱动 DSH 助手(与 Web 同一模型/工具)
|
|
42
|
+
→ 上下文超限时由 dsh-compaction-basic 自动摘要压缩(与 Web 一致)
|
|
43
|
+
→ 回复按 assistant/chunk 流式回发(replyStream),定稿 + response_url
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## 配置项
|
|
47
|
+
|
|
48
|
+
| 配置 | 类型 | 默认 | 说明 |
|
|
49
|
+
| --- | --- | --- | --- |
|
|
50
|
+
| `botLocale` | `zh` \| `en` | `zh` | 机器人回复文案语言 |
|
|
51
|
+
| `maxChatAgents` | number | `40` | 每机器人最多保留的聊天会话数,超出自动淘汰最旧 |
|
|
52
|
+
| `botModel` | `{provider, model}` | 无 | 可选:机器人专用模型(优先于部署默认模型;不填则与 Web 对话一致) |
|
|
53
|
+
| `autoStartWecom` | boolean | `true` | 启动时用已保存的企业微信智能机器人凭据自动连接 |
|
|
54
|
+
| `autoStartTelegram` | boolean | `true` | 启动时用已保存的 Telegram Bot Token 自动连接 |
|
|
55
|
+
| `autoStartDiscord` | boolean | `true` | 启动时用已保存的 Discord Bot Token 自动连接 |
|
|
56
|
+
| `autoStartQQ` | boolean | `true` | 启动时用已保存的 QQ appId/secret 自动连接 |
|
|
57
|
+
| `autoStartEmail` | boolean | `true` | 启动时用已保存的 Email 凭据自动连接(IMAP 轮询) |
|
|
58
|
+
| `groupReply` | boolean | `true` | 是否回复群聊消息(false 时只处理单聊) |
|
|
59
|
+
|
|
60
|
+
## 扩展指南:新增一个平台连接器
|
|
61
|
+
|
|
62
|
+
把某个平台从「凭据 + 测试」升级为「常驻机器人」只需三步:
|
|
63
|
+
|
|
64
|
+
1. **常驻连接类**:仿照 `src/host/wecom-bridge.ts` 写一个 `XxxBridge`——持有平台
|
|
65
|
+
SDK/长连接生命周期(`start/stop/status`),消息事件通过回调上抛:
|
|
66
|
+
```ts
|
|
67
|
+
export interface XxxBridgeCallbacks {
|
|
68
|
+
onStatus(status: BridgeStatus): void
|
|
69
|
+
onText(text: string, frame: unknown): void
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
2. **桥管理接入**:在 `src/host/bridge-manager.ts` 增加对应字段与方法
|
|
73
|
+
(`startXxx(cred)` / `stopXxx()` / `xxxStatus()`),并在 `onText` 里复用
|
|
74
|
+
现有的「每聊天独立会话 + 流式回发」管线(`ensureAgentForKey` + `pendingMap`),
|
|
75
|
+
回复通道换成该平台的 `replyStream` 等价物。
|
|
76
|
+
3. **存储联动**:在 `src/host/routes.ts` 的 `/gateway/save` 与 `/gateway/delete`
|
|
77
|
+
分支中,仿照 `wecom-aibot` 增加「保存即启动 / 删除即停止」;`src/index.ts` 的
|
|
78
|
+
`autoStartXxx` 与平台配置开关同理。
|
|
79
|
+
|
|
80
|
+
测试函数在 `src/host/platforms.ts` 的 `testPlatform` 中增加 case,client 侧无需改动
|
|
81
|
+
(平台表单由 `PlatformDef` 表自动渲染)。
|
|
82
|
+
|
|
83
|
+
## 各平台能力矩阵
|
|
84
|
+
|
|
85
|
+
| 平台 | 凭据保存 | 连接测试 | 常驻机器人 |
|
|
86
|
+
| --- | :-: | :-: | :-: |
|
|
87
|
+
| 企业微信智能机器人 `wecom-aibot` | ✅ | ✅ | ✅ 对话/欢迎语/指令/群聊/主动推送 |
|
|
88
|
+
| Telegram | ✅ | ✅ | ✅ 长轮询 + 流式编辑回复 |
|
|
89
|
+
| Discord | ✅ | ✅ | ✅ WebSocket 网关 + 流式编辑回复(需开启 MESSAGE CONTENT 意图) |
|
|
90
|
+
| QQ | ✅ | ✅ | ✅ access_token + WebSocket 网关 + 被动回复/流式编辑 |
|
|
91
|
+
| 企业微信应用 `wecom` | ✅ | ✅ | ✅ 回调式(应用消息 API 回复;需公网 URL 配置回调) |
|
|
92
|
+
| 微信公众号 `wechat-mp` | ✅ | ✅ | ✅ 回调式(客服消息 API 回复;需公网 URL 配置回调) |
|
|
93
|
+
| WhatsApp | ✅ | ✅ | ✅ Webhook 式(Meta Cloud API 回复;需公网 URL 配置 Webhook) |
|
|
94
|
+
| Email | ✅ | ✅ | ✅ IMAP 轮询收件(993/143,TLS/STARTTLS)+ SMTP 回复(465/587/25);按邮件线程归类会话,Re: 原主题 |
|
|
95
|
+
| Webhooks | ✅(可选签名) | — | ✅ `POST /gateway/webhook/in` 同步回复 |
|
|
96
|
+
| 微信(个人号) | ✅(外部 Wechaty 网关) | 状态轮询 | 需外部网关([契约](wechaty-gateway.md)) |
|
|
97
|
+
|
|
98
|
+
> 所有常驻机器人的消息都走同一管线:每聊天独立 agent 会话 + 上下文自动压缩 +
|
|
99
|
+
> 斜杠命令 + @提及剥离,与 Web 对话一致。Telegram/Discord/QQ 的"流式回复"通过
|
|
100
|
+
> 先发送后渐进编辑(send + edit)实现,受平台限频保护(约 1 次/秒)。
|
|
101
|
+
|
|
102
|
+
## 回调型平台(企业微信应用 / 公众号 / WhatsApp)
|
|
103
|
+
|
|
104
|
+
这三类平台无长连接,由平台服务器向插件注册的回调端点推送消息(`src/host/callback-bridges.ts`):
|
|
105
|
+
|
|
106
|
+
| 平台 | 端点 | 验证 | 回复通道 |
|
|
107
|
+
| --- | --- | --- | --- |
|
|
108
|
+
| 企业微信应用 | `GET/POST /gateway/wecom/callback` | `msg_signature`(SHA1 排序拼接)+ AES 解密 | 应用消息 API(`message/send`,access_token 缓存) |
|
|
109
|
+
| 微信公众号 | `GET/POST /gateway/wechat-mp/callback` | `signature`(SHA1 排序拼接) | 客服消息 API(`custom/send`) |
|
|
110
|
+
| WhatsApp | `GET/POST /gateway/whatsapp/webhook` | `hub.verify_token` | Meta Graph API `messages` |
|
|
111
|
+
|
|
112
|
+
用法:在消息平台页保存凭据(企业微信需额外填回调 Token 与 EncodingAESKey;公众号填回调 Token;
|
|
113
|
+
WhatsApp 的 Token 即 verify token)→ 在对应平台后台把回调 URL 指向 `公网地址 + 端点路径` →
|
|
114
|
+
用户发消息即自动对话(回执 + 完整回复经发送 API 异步送达;`/gateway/list` 显示端点路径)。
|
|
115
|
+
回调端点无需常驻连接,凭据保存即随时可用。
|
|
116
|
+
|
|
117
|
+
## 对外 HTTP 端点
|
|
118
|
+
|
|
119
|
+
| 端点 | 说明 |
|
|
120
|
+
| --- | --- |
|
|
121
|
+
| `POST /gateway/list` | 平台定义 + 状态(不含凭据明文) |
|
|
122
|
+
| `POST /gateway/save` / `delete` / `test` | 凭据管理 |
|
|
123
|
+
| `POST /gateway/send` | 以机器人身份主动推送 markdown 消息 |
|
|
124
|
+
| `POST /gateway/webhook/in` | Webhook 接收(签名校验,见 [webhooks.md](webhooks.md)) |
|
|
125
|
+
| `POST /gateway/wechat-status` | 外部 Wechaty 网关状态轮询 |
|
|
126
|
+
|
|
127
|
+
## 安全
|
|
128
|
+
|
|
129
|
+
- 凭据明文只落盘 `~/.dsh/gateway.json`(权限 0600,原子写入),`/gateway/list` 永不回传
|
|
130
|
+
- Webhook 可配置 HMAC-SHA256 签名密钥,constant-time 校验
|
|
131
|
+
- 机器人与网页会话完全隔离(独立 agent 会话),互不污染上下文
|
package/docs/webhooks.md
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# Webhook 接收端点契约
|
|
2
|
+
|
|
3
|
+
「消息平台」的 Webhooks 平台提供一个本地 HTTP 接收端点:外部系统 POST 一条文本消息,
|
|
4
|
+
插件将其注入隔离的专用 agent 会话,驱动 DSH 助手生成回复,并在同一 HTTP 响应中同步返回。
|
|
5
|
+
|
|
6
|
+
## 端点
|
|
7
|
+
|
|
8
|
+
### `POST /gateway/webhook/in`
|
|
9
|
+
|
|
10
|
+
**请求体(`application/json`)**——三种字段任选其一:
|
|
11
|
+
|
|
12
|
+
```jsonc
|
|
13
|
+
{ "text": "帮我总结一下这个仓库的 README" }
|
|
14
|
+
// 或 { "content": "..." }
|
|
15
|
+
// 或 { "message": "..." }
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
**请求头**
|
|
19
|
+
|
|
20
|
+
| 头 | 说明 |
|
|
21
|
+
| --- | --- |
|
|
22
|
+
| `Content-Type: application/json` | 必填 |
|
|
23
|
+
| `X-Gateway-Signature` | 配置了签名密钥时必填:`hex(HMAC-SHA256(secret, 原始请求体))` |
|
|
24
|
+
|
|
25
|
+
**响应(成功,HTTP 200)**
|
|
26
|
+
|
|
27
|
+
```jsonc
|
|
28
|
+
{ "ok": true, "value": { "reply": "这是助手生成的完整回复……" } }
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
**错误响应**
|
|
32
|
+
|
|
33
|
+
| HTTP | 场景 |
|
|
34
|
+
| --- | --- |
|
|
35
|
+
| `400` | 请求体为空 / 缺少 `text` / `content` / `message` 字段或全部为空 |
|
|
36
|
+
| `401` | 配置了签名密钥但 `X-Gateway-Signature` 缺失或不匹配 |
|
|
37
|
+
| `409` | 另一条外部消息正在处理中(单槽位,请求被拒绝) |
|
|
38
|
+
| `500` | 专用 agent 不可用等内部错误 |
|
|
39
|
+
|
|
40
|
+
## 签名校验
|
|
41
|
+
|
|
42
|
+
- 在「消息平台」页面为 **Webhooks** 平台保存「签名密钥」后,端点要求每个请求携带
|
|
43
|
+
`X-Gateway-Signature` 头
|
|
44
|
+
- 签名 = `HMAC-SHA256(secret, rawBody)` 的十六进制小写字符串(对**原始请求体**计算,不是 JSON 序列化后的字符串)
|
|
45
|
+
- 未配置签名密钥时端点完全开放(任何请求体都会被处理)
|
|
46
|
+
|
|
47
|
+
### 签名示例(Node)
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { createHmac } from 'node:crypto'
|
|
51
|
+
|
|
52
|
+
const secret = 'your-saved-signing-secret'
|
|
53
|
+
const body = JSON.stringify({ text: '你好' })
|
|
54
|
+
const signature = createHmac('sha256', secret).update(body).digest('hex')
|
|
55
|
+
|
|
56
|
+
await fetch('http://127.0.0.1:3080/gateway/webhook/in', {
|
|
57
|
+
method: 'POST',
|
|
58
|
+
headers: { 'content-type': 'application/json', 'x-gateway-signature': signature },
|
|
59
|
+
body,
|
|
60
|
+
})
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### 签名示例(curl)
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
SECRET='your-saved-signing-secret'
|
|
67
|
+
BODY='{"text":"你好"}'
|
|
68
|
+
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" -hex | awk '{print $2}')
|
|
69
|
+
|
|
70
|
+
curl -X POST http://127.0.0.1:3080/gateway/webhook/in \
|
|
71
|
+
-H 'content-type: application/json' \
|
|
72
|
+
-H "x-gateway-signature: $SIG" \
|
|
73
|
+
-d "$BODY"
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## 说明
|
|
77
|
+
|
|
78
|
+
- 回复为同步等待:插件轮询专用 agent 会话的事件流直至出现完整回复(默认 90 秒超时)
|
|
79
|
+
- 同一时间只处理一条外部消息:Webhook 与企微智能机器人共享同一个专用 agent 会话与单槽位
|
|
80
|
+
- 端点挂在 DSH Web 的共享 webserver 上(默认 `http://127.0.0.1:3080`);如需接收公网请求,
|
|
81
|
+
需自行配置反代 / 内网穿透
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# 微信(Wechaty)HTTP 网关契约
|
|
2
|
+
|
|
3
|
+
本插件不内置微信个人号连接器(需第三方框架,如 Wechaty + wechaty-puppet-wechat 扫码登录),
|
|
4
|
+
而是通过一个**本机 HTTP 网关**对接。在「消息平台」页面配置微信平台的 `gatewayUrl` 与可选
|
|
5
|
+
`token` 后,插件会轮询该网关获取登录状态 / 二维码。
|
|
6
|
+
|
|
7
|
+
## 端点
|
|
8
|
+
|
|
9
|
+
### `GET {gatewayUrl}/status`
|
|
10
|
+
|
|
11
|
+
返回当前登录状态。`gatewayUrl` 以用户在表单中填写的值(结尾 `/` 会被去除)为准。
|
|
12
|
+
|
|
13
|
+
**请求头**
|
|
14
|
+
|
|
15
|
+
| 头 | 说明 |
|
|
16
|
+
| --- | --- |
|
|
17
|
+
| `Accept: application/json` | 固定发送 |
|
|
18
|
+
| `Authorization: Bearer <token>` | 仅在配置了 `token` 时发送 |
|
|
19
|
+
|
|
20
|
+
**响应(HTTP 200,`application/json`)**
|
|
21
|
+
|
|
22
|
+
```jsonc
|
|
23
|
+
{
|
|
24
|
+
"loggedIn": false, // 是否已登录
|
|
25
|
+
"name": "", // 已登录时的微信昵称(未登录可为空)
|
|
26
|
+
"qrcode": "base64...", // 未登录时的登录二维码(base64 图片,可空)
|
|
27
|
+
"qrcodeUrl": "https://..." // 二维码图片 URL(可空,优先展示)
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
| 字段 | 类型 | 说明 |
|
|
32
|
+
| --- | --- | --- |
|
|
33
|
+
| `loggedIn` | boolean | 是否已登录 |
|
|
34
|
+
| `name` | string | 已登录时的账号昵称 |
|
|
35
|
+
| `qrcode` | string \| null | 登录二维码(base64) |
|
|
36
|
+
| `qrcodeUrl` | string \| null | 登录二维码图片 URL |
|
|
37
|
+
|
|
38
|
+
**非 200 响应**:插件记录 `HTTP <status>` 并标记为「未登录」;请求失败(网络错误 / 超时,
|
|
39
|
+
超时 8 秒)记录错误消息。
|
|
40
|
+
|
|
41
|
+
## 最小实现示例(Node)
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { createServer } from 'node:http'
|
|
45
|
+
|
|
46
|
+
let loggedIn = false
|
|
47
|
+
let name = ''
|
|
48
|
+
let qrcode = 'data:image/png;base64,...' // 由 wechaty getQrCode() 生成
|
|
49
|
+
|
|
50
|
+
createServer((req, res) => {
|
|
51
|
+
if (req.url === '/status') {
|
|
52
|
+
res.writeHead(200, { 'content-type': 'application/json' })
|
|
53
|
+
res.end(JSON.stringify({ loggedIn, name, qrcode: loggedIn ? null : qrcode, qrcodeUrl: null }))
|
|
54
|
+
return
|
|
55
|
+
}
|
|
56
|
+
res.writeHead(404).end()
|
|
57
|
+
}).listen(8787, () => console.log('wechaty gateway: http://127.0.0.1:8787'))
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
插件侧填入 `gatewayUrl = http://127.0.0.1:8787` 即可在「消息平台」页面看到扫码二维码与登录状态。
|
|
61
|
+
|
|
62
|
+
## 说明
|
|
63
|
+
|
|
64
|
+
- 状态由插件以请求驱动轮询(保存 / 打开页面时查询),不是推送
|
|
65
|
+
- `token` 为可选的网关访问令牌;网关需自行校验 `Authorization: Bearer` 头
|
|
66
|
+
- 凭据(含 `token`)只存 `~/.dsh/gateway.json`,不回传浏览器
|