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/lib/index.js ADDED
@@ -0,0 +1,2768 @@
1
+ // src/host/bridge-manager.ts
2
+ import { installModelSelection } from "@deepseek-ai/dsh-agent";
3
+ import { SessionId } from "@deepseek-ai/dsh-session";
4
+ import { randomUUID } from "node:crypto";
5
+ import { MessageId } from "@deepseek-ai/dsh-llm";
6
+
7
+ // src/host/bot-i18n.ts
8
+ var MSGS = {
9
+ zh: {
10
+ ack: "\u6B63\u5728\u5904\u7406\u2026",
11
+ busy: "\u23F3 \u4E0A\u4E00\u6761\u6D88\u606F\u8FD8\u5728\u5904\u7406\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",
12
+ noAgent: "\u26A0\uFE0F DSH \u52A9\u624B\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",
13
+ welcome: "\u60A8\u597D\uFF01\u6211\u662F\u667A\u80FD\u52A9\u624B \u{1F916}\n\n- \u76F4\u63A5\u53D1\u6D88\u606F\u548C\u6211 AI \u5BF9\u8BDD\n- \u6BCF\u4E2A\u804A\u5929\u81EA\u52A8\u62E5\u6709\u72EC\u7ACB\u4F1A\u8BDD\uFF0C\u4E0A\u4E0B\u6587\u8D85\u957F\u81EA\u52A8\u538B\u7F29\uFF0C\u548C Web \u5BF9\u8BDD\u4E00\u81F4\n- \u8F93\u5165 /help \u67E5\u770B\u5168\u90E8\u6307\u4EE4",
14
+ help: "\u{1F916} **\u667A\u80FD\u52A9\u624B\u6307\u4EE4**\n- \u76F4\u63A5\u53D1\u6D88\u606F \u2192 AI \u5BF9\u8BDD\uFF08\u4E0E Web \u4E00\u81F4\uFF1A\u72EC\u7ACB\u4F1A\u8BDD + \u81EA\u52A8\u538B\u7F29\uFF09\n- `/new` \u6216 `/clear` \u2192 \u5F00\u542F\u65B0\u4F1A\u8BDD\uFF08\u6E05\u7A7A\u672C\u804A\u5929\u4E0A\u4E0B\u6587\uFF09\n- `/time` \u2192 \u5F53\u524D\u65F6\u95F4\n- `/status` \u2192 \u67E5\u770B\u673A\u5668\u4EBA\u72B6\u6001\n- `/help` \u2192 \u67E5\u770B\u6307\u4EE4",
15
+ newOk: "\u2705 \u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\uFF0C\u4E4B\u524D\u7684\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u5DF2\u6E05\u7A7A",
16
+ newIdle: "\u2139\uFE0F \u5F53\u524D\u4F1A\u8BDD\u5DF2\u662F\u65B0\u4F1A\u8BDD",
17
+ timeout: "\u26A0\uFE0F \u56DE\u590D\u8D85\u65F6\u4E86\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u4E00\u6B21",
18
+ statusTitle: "\u{1F4E1} **\u673A\u5668\u4EBA\u72B6\u6001**",
19
+ statusOnline: "\u2705 \u5728\u7EBF",
20
+ statusOffline: "\u274C \u79BB\u7EBF",
21
+ statusBotId: "BotID",
22
+ statusChats: "\u6D3B\u8DC3\u4F1A\u8BDD",
23
+ statusAgent: "DSH \u52A9\u624B",
24
+ statusTime: "\u65F6\u95F4",
25
+ statusAvailable: "\u53EF\u7528",
26
+ statusUnavailable: "\u4E0D\u53EF\u7528",
27
+ timePrefix: "\u{1F550}"
28
+ },
29
+ en: {
30
+ ack: "Processing\u2026",
31
+ busy: "\u23F3 Still processing your previous message, please wait",
32
+ noAgent: "\u26A0\uFE0F DSH assistant is unavailable, please try again later",
33
+ welcome: "Hi! I am your AI assistant \u{1F916}\n\n- Chat with me directly\n- Each chat gets its own session; long contexts are auto-compressed, same as the web\n- Type /help for all commands",
34
+ help: "\u{1F916} **Assistant commands**\n- Send a message \u2192 AI chat (same as web: own session + auto compression)\n- `/new` or `/clear` \u2192 start a new session (clear this chat context)\n- `/time` \u2192 current time\n- `/status` \u2192 bot status\n- `/help` \u2192 this help",
35
+ newOk: "\u2705 New session started, previous context cleared",
36
+ newIdle: "\u2139\uFE0F This chat already has a fresh session",
37
+ timeout: "\u26A0\uFE0F Reply timed out, please try again in a moment",
38
+ statusTitle: "\u{1F4E1} **Bot status**",
39
+ statusOnline: "\u2705 Online",
40
+ statusOffline: "\u274C Offline",
41
+ statusBotId: "Bot ID",
42
+ statusChats: "Active chats",
43
+ statusAgent: "DSH assistant",
44
+ statusTime: "Time",
45
+ statusAvailable: "available",
46
+ statusUnavailable: "unavailable",
47
+ timePrefix: "\u{1F550}"
48
+ }
49
+ };
50
+ function botText(locale, key) {
51
+ return MSGS[locale][key] ?? MSGS.zh[key] ?? key;
52
+ }
53
+
54
+ // src/host/wecom-bridge.ts
55
+ import { WSClient } from "@wecom/aibot-node-sdk";
56
+ var WecomBridge = class {
57
+ constructor(cred, callbacks) {
58
+ this.cred = cred;
59
+ this.callbacks = callbacks;
60
+ }
61
+ client = null;
62
+ started = false;
63
+ status = { state: "idle", detail: "", connectedAt: null };
64
+ setStatus(state, detail = "") {
65
+ this.status = {
66
+ state,
67
+ detail,
68
+ connectedAt: state === "connected" ? Date.now() : this.status.connectedAt
69
+ };
70
+ this.callbacks.onStatus(this.status);
71
+ }
72
+ /** 建立常驻连接(断线由 SDK 自动指数退避重连)。 */
73
+ start() {
74
+ if (this.started) return;
75
+ this.started = true;
76
+ this.setStatus("connecting");
77
+ const client = new WSClient({ botId: this.cred.botId, secret: this.cred.secret });
78
+ this.client = client;
79
+ client.on("authenticated", () => this.setStatus("connected", `botId ${this.cred.botId}`));
80
+ client.on("message.text", (frame) => {
81
+ const content = frame.body?.text?.content ?? "";
82
+ if (content.trim() !== "") this.callbacks.onText(content, frame);
83
+ });
84
+ client.on("event.enter_chat", (frame) => {
85
+ this.callbacks.onEnter(frame);
86
+ });
87
+ client.on("error", (err) => {
88
+ if (this.status.state !== "connected") this.setStatus("error", err?.message ?? "\u8FDE\u63A5\u9519\u8BEF");
89
+ });
90
+ client.connect();
91
+ }
92
+ /** 经 response_url(企业微信官方 HTTP 通道)发送完整回复,无超时限制。 */
93
+ async postResponse(url, content) {
94
+ try {
95
+ const response = await fetch(url, {
96
+ method: "POST",
97
+ headers: { "content-type": "application/json" },
98
+ body: JSON.stringify({ msgtype: "markdown", markdown: { content } })
99
+ });
100
+ if (!response.ok) console.error("[dsh-message-gateway] response_url http", response.status);
101
+ return response.ok;
102
+ } catch (error) {
103
+ console.error("[dsh-message-gateway] response_url failed", error);
104
+ return false;
105
+ }
106
+ }
107
+ /** 流式回复:全量更新内容,finish=true 定稿。 */
108
+ async streamReply(frame, streamId, content, finish) {
109
+ try {
110
+ await this.client?.replyStream(frame, streamId, content, finish);
111
+ } catch (error) {
112
+ console.error("[dsh-message-gateway] stream reply failed", error);
113
+ }
114
+ }
115
+ /** 主动向会话发送 markdown 消息(chatid:单聊=userid,群聊=群 ID)。 */
116
+ async sendMessage(chatid, content) {
117
+ try {
118
+ await this.client?.sendMessage(chatid, { msgtype: "markdown", markdown: { content } });
119
+ return true;
120
+ } catch (error) {
121
+ console.error("[dsh-message-gateway] sendMessage failed", error);
122
+ return false;
123
+ }
124
+ }
125
+ /** 回复欢迎语(enter_chat 事件)。 */
126
+ async welcome(frame, content) {
127
+ try {
128
+ await this.client?.replyWelcome(frame, { msgtype: "text", text: { content } });
129
+ } catch (error) {
130
+ console.error("[dsh-message-gateway] welcome reply failed", error);
131
+ }
132
+ }
133
+ /** 停止常驻连接。 */
134
+ stop() {
135
+ this.started = false;
136
+ this.client?.disconnect();
137
+ this.client = null;
138
+ this.setStatus("idle");
139
+ }
140
+ };
141
+
142
+ // src/host/telegram-bridge.ts
143
+ var EDIT_INTERVAL_MS = 1200;
144
+ var MSG_LIMIT = 4096;
145
+ var POLL_TIMEOUT = 25;
146
+ var TelegramBridge = class {
147
+ constructor(token, callbacks) {
148
+ this.token = token;
149
+ this.callbacks = callbacks;
150
+ }
151
+ stopped = false;
152
+ pollTimer = null;
153
+ offset = 0;
154
+ /** streamId → 已发送消息(用于渐进编辑)。 */
155
+ streams = /* @__PURE__ */ new Map();
156
+ /** streamId → 最新待推送内容(流式合并,单 worker 消费)。 */
157
+ state = /* @__PURE__ */ new Map();
158
+ working = /* @__PURE__ */ new Set();
159
+ status = { state: "idle", detail: "", connectedAt: null };
160
+ setStatus(state, detail = "") {
161
+ this.status = { state, detail, connectedAt: state === "connected" ? Date.now() : this.status.connectedAt };
162
+ this.callbacks.onStatus(this.status);
163
+ }
164
+ /** 启动长轮询。 */
165
+ start() {
166
+ if (!this.stopped && this.pollTimer !== null) return;
167
+ this.stopped = false;
168
+ this.setStatus("connecting", "long polling");
169
+ this.pollTimer = setTimeout(() => void this.poll(), 0);
170
+ }
171
+ async api(method, params, timeoutMs = 15e3) {
172
+ const controller = new AbortController();
173
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
174
+ try {
175
+ const response = await fetch(`https://api.telegram.org/bot${this.token}/${method}`, {
176
+ method: "POST",
177
+ headers: { "content-type": "application/json" },
178
+ body: JSON.stringify(params),
179
+ signal: controller.signal
180
+ });
181
+ const body = await response.json();
182
+ if (body.ok === true) return body.result;
183
+ console.warn("[dsh-message-gateway] telegram api", method, body.description ?? `HTTP ${response.status}`);
184
+ return null;
185
+ } catch (error) {
186
+ console.warn("[dsh-message-gateway] telegram api failed", method, String(error));
187
+ return null;
188
+ } finally {
189
+ clearTimeout(timer);
190
+ }
191
+ }
192
+ async poll() {
193
+ if (this.stopped) return;
194
+ const result = await this.api(
195
+ "getUpdates",
196
+ { offset: this.offset, timeout: POLL_TIMEOUT, allowed_updates: ["message"] },
197
+ (POLL_TIMEOUT + 15) * 1e3
198
+ );
199
+ if (this.stopped) return;
200
+ if (result !== null) {
201
+ this.setStatus("connected", "telegram");
202
+ const updates = result;
203
+ for (const update of updates) {
204
+ this.offset = Math.max(this.offset, update.update_id + 1);
205
+ if (update.message !== void 0) this.handleMessage(update.message);
206
+ }
207
+ } else {
208
+ this.setStatus("error", "poll failed");
209
+ await new Promise((resolve) => setTimeout(resolve, 3e3));
210
+ }
211
+ if (!this.stopped) this.pollTimer = setTimeout(() => void this.poll(), 0);
212
+ }
213
+ handleMessage(m) {
214
+ const from = m.from;
215
+ if (from?.is_bot === true) return;
216
+ const text = typeof m.text === "string" ? m.text.trim() : "";
217
+ if (text === "") return;
218
+ const chat = m.chat;
219
+ if (chat === void 0) return;
220
+ const frame = { chatId: chat.id, messageId: m.message_id ?? 0, chatType: chat.type ?? "private" };
221
+ const sink = {
222
+ stream: (f, sid, content, finish) => void this.streamReply(f, sid, content, finish)
223
+ };
224
+ const identity = {
225
+ key: `telegram:${chat.id}`,
226
+ frame,
227
+ sink,
228
+ chatType: (chat.type ?? "private") === "private" ? "single" : "group"
229
+ };
230
+ console.log("[dsh-message-gateway] telegram text", { chatId: chat.id, text: text.slice(0, 60) });
231
+ this.callbacks.onText(text, identity);
232
+ }
233
+ /** 流式回复:状态合并 + 单 worker——首次 sendMessage,随后 editMessageText 渐进更新(限频)。 */
234
+ async streamReply(frame, streamId, content, finish) {
235
+ const prev = this.state.get(streamId);
236
+ this.state.set(streamId, { content, finish: finish || (prev?.finish ?? false) });
237
+ if (this.working.has(streamId)) return;
238
+ this.working.add(streamId);
239
+ try {
240
+ for (let guard = 0; guard < 200; guard += 1) {
241
+ const current = this.state.get(streamId);
242
+ if (current === void 0) break;
243
+ const text = current.content === "" ? " " : current.content;
244
+ const existing = this.streams.get(streamId);
245
+ if (existing === void 0) {
246
+ if (current.content === "" && !current.finish) break;
247
+ const result = await this.sendText(frame.chatId, text);
248
+ if (result === null) break;
249
+ this.streams.set(streamId, { chatId: frame.chatId, messageId: result.messageId, lastEdit: Date.now() });
250
+ if (current.finish || this.state.get(streamId).content === current.content) break;
251
+ continue;
252
+ }
253
+ const wait = EDIT_INTERVAL_MS - (Date.now() - existing.lastEdit);
254
+ if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
255
+ existing.lastEdit = Date.now();
256
+ const ok = await this.editText(existing.chatId, existing.messageId, text);
257
+ if (!ok && current.finish) {
258
+ this.streams.delete(streamId);
259
+ break;
260
+ }
261
+ if (current.finish || this.state.get(streamId).content === current.content) break;
262
+ }
263
+ } catch (error) {
264
+ console.error("[dsh-message-gateway] telegram reply failed", error);
265
+ } finally {
266
+ this.working.delete(streamId);
267
+ }
268
+ }
269
+ /** 发送文本(Markdown 失败自动降级纯文本)。 */
270
+ async sendText(chatId, text) {
271
+ const body = { chat_id: chatId, text: text.slice(0, MSG_LIMIT), parse_mode: "Markdown", disable_web_page_preview: true };
272
+ const result = await this.api("sendMessage", body);
273
+ if (result?.message_id !== void 0) return { messageId: result.message_id };
274
+ const plain = await this.api("sendMessage", { chat_id: chatId, text: text.slice(0, MSG_LIMIT), disable_web_page_preview: true });
275
+ return plain?.message_id !== void 0 ? { messageId: plain.message_id } : null;
276
+ }
277
+ /** 编辑消息(Markdown 失败自动降级纯文本)。 */
278
+ async editText(chatId, messageId, text) {
279
+ const body = { chat_id: chatId, message_id: messageId, text: text.slice(0, MSG_LIMIT), parse_mode: "Markdown" };
280
+ if (await this.api("editMessageText", body) !== null) return true;
281
+ const plain = await this.api("editMessageText", { chat_id: chatId, message_id: messageId, text: text.slice(0, MSG_LIMIT) }) !== null;
282
+ return plain;
283
+ }
284
+ /** 停止长轮询。 */
285
+ stop() {
286
+ this.stopped = true;
287
+ if (this.pollTimer !== null) clearTimeout(this.pollTimer);
288
+ this.pollTimer = null;
289
+ this.streams.clear();
290
+ this.setStatus("idle");
291
+ }
292
+ };
293
+
294
+ // src/host/discord-bridge.ts
295
+ var GATEWAY_URL = "wss://gateway.discord.gg/?v=10&encoding=json";
296
+ var REST = "https://discord.com/api/v10";
297
+ var INTENTS = 1 << 0 | 1 << 9 | 1 << 12 | 1 << 15;
298
+ var EDIT_INTERVAL_MS2 = 1200;
299
+ var MSG_LIMIT2 = 2e3;
300
+ var DiscordBridge = class {
301
+ constructor(token, callbacks) {
302
+ this.token = token;
303
+ this.callbacks = callbacks;
304
+ }
305
+ ws = null;
306
+ stopped = false;
307
+ heartbeat = null;
308
+ seq = null;
309
+ /** streamId → 已发送消息(用于渐进编辑)。 */
310
+ streams = /* @__PURE__ */ new Map();
311
+ /** streamId → 最新待推送内容(流式合并,单 worker 消费)。 */
312
+ state = /* @__PURE__ */ new Map();
313
+ working = /* @__PURE__ */ new Set();
314
+ status = { state: "idle", detail: "", connectedAt: null };
315
+ setStatus(state, detail = "") {
316
+ this.status = { state, detail, connectedAt: state === "connected" ? Date.now() : this.status.connectedAt };
317
+ this.callbacks.onStatus(this.status);
318
+ }
319
+ /** 启动网关连接。 */
320
+ start() {
321
+ if (!this.stopped && this.ws !== null) return;
322
+ this.stopped = false;
323
+ this.setStatus("connecting", "gateway");
324
+ this.connect();
325
+ }
326
+ connect() {
327
+ if (this.stopped) return;
328
+ let ws;
329
+ try {
330
+ ws = new WebSocket(GATEWAY_URL);
331
+ } catch (error) {
332
+ console.error("[dsh-message-gateway] discord ws create failed", error);
333
+ this.setStatus("error", "ws create failed");
334
+ return;
335
+ }
336
+ this.ws = ws;
337
+ ws.onopen = () => console.log("[dsh-message-gateway] discord gateway open");
338
+ ws.onmessage = (event) => this.onMessage(String(event.data));
339
+ ws.onerror = () => ws.close();
340
+ ws.onclose = () => {
341
+ this.clearHeartbeat();
342
+ this.ws = null;
343
+ if (!this.stopped) {
344
+ console.warn("[dsh-message-gateway] discord gateway closed, reconnect in 3s");
345
+ setTimeout(() => this.connect(), 3e3);
346
+ }
347
+ };
348
+ }
349
+ onMessage(raw) {
350
+ let payload;
351
+ try {
352
+ payload = JSON.parse(raw);
353
+ } catch {
354
+ return;
355
+ }
356
+ if (payload.s !== null && payload.s !== void 0) this.seq = payload.s;
357
+ switch (payload.op) {
358
+ case 10: {
359
+ const d = payload.d;
360
+ this.startHeartbeat(d.heartbeat_interval);
361
+ this.identify();
362
+ break;
363
+ }
364
+ case 1: {
365
+ this.sendOp(1, this.seq);
366
+ break;
367
+ }
368
+ case 0: {
369
+ if (payload.t === "READY") {
370
+ this.setStatus("connected", "discord");
371
+ console.log("[dsh-message-gateway] discord READY");
372
+ } else if (payload.t === "MESSAGE_CREATE") {
373
+ this.handleMessage(payload.d);
374
+ }
375
+ break;
376
+ }
377
+ case 7: {
378
+ this.ws?.close();
379
+ break;
380
+ }
381
+ }
382
+ }
383
+ sendOp(op, d) {
384
+ if (this.ws === null || this.ws.readyState !== WebSocket.OPEN) return;
385
+ this.ws.send(JSON.stringify({ op, d }));
386
+ }
387
+ identify() {
388
+ this.sendOp(2, {
389
+ token: this.token,
390
+ intents: INTENTS,
391
+ properties: { os: "linux", browser: "dsh-message-gateway", device: "dsh-message-gateway" }
392
+ });
393
+ }
394
+ startHeartbeat(interval) {
395
+ this.clearHeartbeat();
396
+ this.heartbeat = setInterval(() => this.sendOp(1, this.seq), interval);
397
+ this.heartbeat.unref?.();
398
+ }
399
+ clearHeartbeat() {
400
+ if (this.heartbeat !== null) {
401
+ clearInterval(this.heartbeat);
402
+ this.heartbeat = null;
403
+ }
404
+ }
405
+ async rest(method, path, body) {
406
+ const controller = new AbortController();
407
+ const timer = setTimeout(() => controller.abort(), 15e3);
408
+ try {
409
+ const response = await fetch(`${REST}${path}`, {
410
+ method,
411
+ headers: { authorization: `Bot ${this.token}`, "content-type": "application/json" },
412
+ body: body === void 0 ? void 0 : JSON.stringify(body),
413
+ signal: controller.signal
414
+ });
415
+ if (!response.ok) {
416
+ console.warn("[dsh-message-gateway] discord rest", method, path, response.status);
417
+ return null;
418
+ }
419
+ return await response.json();
420
+ } catch (error) {
421
+ console.warn("[dsh-message-gateway] discord rest failed", method, path, String(error));
422
+ return null;
423
+ } finally {
424
+ clearTimeout(timer);
425
+ }
426
+ }
427
+ handleMessage(d) {
428
+ const author = d.author;
429
+ if (author?.bot === true) return;
430
+ const text = typeof d.content === "string" ? d.content.trim() : "";
431
+ if (text === "") return;
432
+ const channelId = String(d.channel_id ?? "");
433
+ if (channelId === "") return;
434
+ const guildId = typeof d.guild_id === "string" ? d.guild_id : "";
435
+ const frame = { channelId, messageId: String(d.id ?? ""), guildId };
436
+ const sink = {
437
+ stream: (f, sid, content, finish) => void this.streamReply(f, sid, content, finish)
438
+ };
439
+ const identity = {
440
+ key: `discord:${channelId}`,
441
+ frame,
442
+ sink,
443
+ chatType: guildId === "" ? "single" : "group"
444
+ };
445
+ console.log("[dsh-message-gateway] discord text", { channelId, text: text.slice(0, 60) });
446
+ this.callbacks.onText(text, identity);
447
+ }
448
+ /** 流式回复:状态合并 + 单 worker——首次发送消息,随后 PATCH 渐进更新(限频)。 */
449
+ async streamReply(frame, streamId, content, finish) {
450
+ const prev = this.state.get(streamId);
451
+ this.state.set(streamId, { content, finish: finish || (prev?.finish ?? false) });
452
+ if (this.working.has(streamId)) return;
453
+ this.working.add(streamId);
454
+ try {
455
+ for (let guard = 0; guard < 200; guard += 1) {
456
+ const current = this.state.get(streamId);
457
+ if (current === void 0) break;
458
+ const text = (current.content === "" ? " " : current.content).slice(0, MSG_LIMIT2);
459
+ const existing = this.streams.get(streamId);
460
+ if (existing === void 0) {
461
+ if (current.content === "" && !current.finish) break;
462
+ const result = await this.rest("POST", `/channels/${frame.channelId}/messages`, { content: text });
463
+ if (result?.id === void 0) break;
464
+ this.streams.set(streamId, { channelId: frame.channelId, messageId: result.id, lastEdit: Date.now() });
465
+ if (current.finish || this.state.get(streamId).content === current.content) break;
466
+ continue;
467
+ }
468
+ const wait = EDIT_INTERVAL_MS2 - (Date.now() - existing.lastEdit);
469
+ if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
470
+ existing.lastEdit = Date.now();
471
+ await this.rest("PATCH", `/channels/${existing.channelId}/messages/${existing.messageId}`, { content: text });
472
+ if (current.finish || this.state.get(streamId).content === current.content) break;
473
+ }
474
+ } catch (error) {
475
+ console.error("[dsh-message-gateway] discord reply failed", error);
476
+ } finally {
477
+ this.working.delete(streamId);
478
+ }
479
+ }
480
+ /** 停止网关连接。 */
481
+ stop() {
482
+ this.stopped = true;
483
+ this.clearHeartbeat();
484
+ this.streams.clear();
485
+ this.ws?.close();
486
+ this.ws = null;
487
+ this.setStatus("idle");
488
+ }
489
+ };
490
+
491
+ // src/host/qq-bridge.ts
492
+ var TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken";
493
+ var REST2 = "https://api.sgroup.qq.com";
494
+ var GATEWAY = "wss://api.sgroup.qq.com/?v=1&encoding=json";
495
+ var INTENTS2 = 1 << 9 | 1 << 12 | 1 << 30;
496
+ var EDIT_INTERVAL_MS3 = 1200;
497
+ var MSG_LIMIT3 = 2e3;
498
+ var QQBridge = class {
499
+ constructor(appId, secret, callbacks) {
500
+ this.appId = appId;
501
+ this.secret = secret;
502
+ this.callbacks = callbacks;
503
+ }
504
+ ws = null;
505
+ stopped = false;
506
+ heartbeat = null;
507
+ seq = null;
508
+ accessToken = null;
509
+ /** streamId → 已发送消息(用于渐进编辑)。 */
510
+ streams = /* @__PURE__ */ new Map();
511
+ /** streamId → 最新待推送内容(流式合并,单 worker 消费)。 */
512
+ state = /* @__PURE__ */ new Map();
513
+ working = /* @__PURE__ */ new Set();
514
+ status = { state: "idle", detail: "", connectedAt: null };
515
+ setStatus(state, detail = "") {
516
+ this.status = { state, detail, connectedAt: state === "connected" ? Date.now() : this.status.connectedAt };
517
+ this.callbacks.onStatus(this.status);
518
+ }
519
+ /** 启动:先取 access_token,再连网关。 */
520
+ start() {
521
+ if (!this.stopped && this.ws !== null) return;
522
+ this.stopped = false;
523
+ this.setStatus("connecting", "access token");
524
+ void this.getAccessToken().then((token) => {
525
+ if (this.stopped) return;
526
+ if (token === null) {
527
+ this.setStatus("error", "access token failed");
528
+ return;
529
+ }
530
+ this.accessToken = token;
531
+ this.setStatus("connecting", "gateway");
532
+ this.connect();
533
+ });
534
+ }
535
+ async getAccessToken() {
536
+ const controller = new AbortController();
537
+ const timer = setTimeout(() => controller.abort(), 15e3);
538
+ try {
539
+ const response = await fetch(TOKEN_URL, {
540
+ method: "POST",
541
+ headers: { "content-type": "application/json" },
542
+ body: JSON.stringify({ appId: this.appId, clientSecret: this.secret }),
543
+ signal: controller.signal
544
+ });
545
+ const body = await response.json();
546
+ if (response.ok && body.access_token !== void 0 && body.access_token !== "") {
547
+ return body.access_token;
548
+ }
549
+ console.warn("[dsh-message-gateway] qq access token failed", response.status, body.message ?? body.code);
550
+ return null;
551
+ } catch (error) {
552
+ console.warn("[dsh-message-gateway] qq access token error", String(error));
553
+ return null;
554
+ } finally {
555
+ clearTimeout(timer);
556
+ }
557
+ }
558
+ connect() {
559
+ if (this.stopped) return;
560
+ let ws;
561
+ try {
562
+ ws = new WebSocket(GATEWAY);
563
+ } catch (error) {
564
+ console.error("[dsh-message-gateway] qq ws create failed", error);
565
+ this.setStatus("error", "ws create failed");
566
+ return;
567
+ }
568
+ this.ws = ws;
569
+ ws.onopen = () => console.log("[dsh-message-gateway] qq gateway open");
570
+ ws.onmessage = (event) => this.onMessage(String(event.data));
571
+ ws.onerror = () => ws.close();
572
+ ws.onclose = () => {
573
+ this.clearHeartbeat();
574
+ this.ws = null;
575
+ if (!this.stopped) {
576
+ console.warn("[dsh-message-gateway] qq gateway closed, reconnect in 3s");
577
+ setTimeout(() => this.connect(), 3e3);
578
+ }
579
+ };
580
+ }
581
+ onMessage(raw) {
582
+ let payload;
583
+ try {
584
+ payload = JSON.parse(raw);
585
+ } catch {
586
+ return;
587
+ }
588
+ if (payload.s !== null && payload.s !== void 0) this.seq = payload.s;
589
+ switch (payload.op) {
590
+ case 10: {
591
+ const d = payload.d;
592
+ this.startHeartbeat(d.heartbeat_interval);
593
+ this.identify();
594
+ break;
595
+ }
596
+ case 1: {
597
+ this.sendOp(1, this.seq);
598
+ break;
599
+ }
600
+ case 0: {
601
+ if (payload.t === "READY") {
602
+ this.setStatus("connected", "qq");
603
+ console.log("[dsh-message-gateway] qq READY");
604
+ } else if (payload.t === "MESSAGE_CREATE" || payload.t === "DIRECT_MESSAGE_CREATE") {
605
+ this.handleMessage(payload.d);
606
+ }
607
+ break;
608
+ }
609
+ case 7: {
610
+ this.ws?.close();
611
+ break;
612
+ }
613
+ }
614
+ }
615
+ sendOp(op, d) {
616
+ if (this.ws === null || this.ws.readyState !== WebSocket.OPEN) return;
617
+ this.ws.send(JSON.stringify({ op, d }));
618
+ }
619
+ identify() {
620
+ this.sendOp(2, {
621
+ token: this.accessToken,
622
+ intents: INTENTS2,
623
+ shard: [0, 1]
624
+ });
625
+ }
626
+ startHeartbeat(interval) {
627
+ this.clearHeartbeat();
628
+ this.heartbeat = setInterval(() => this.sendOp(1, this.seq), interval);
629
+ this.heartbeat.unref?.();
630
+ }
631
+ clearHeartbeat() {
632
+ if (this.heartbeat !== null) {
633
+ clearInterval(this.heartbeat);
634
+ this.heartbeat = null;
635
+ }
636
+ }
637
+ async rest(method, path, body) {
638
+ const controller = new AbortController();
639
+ const timer = setTimeout(() => controller.abort(), 15e3);
640
+ try {
641
+ const response = await fetch(`${REST2}${path}`, {
642
+ method,
643
+ headers: {
644
+ authorization: `Bot ${this.accessToken ?? ""}`,
645
+ "content-type": "application/json"
646
+ },
647
+ body: body === void 0 ? void 0 : JSON.stringify(body),
648
+ signal: controller.signal
649
+ });
650
+ if (!response.ok) {
651
+ console.warn("[dsh-message-gateway] qq rest", method, path, response.status);
652
+ return null;
653
+ }
654
+ return await response.json();
655
+ } catch (error) {
656
+ console.warn("[dsh-message-gateway] qq rest failed", method, path, String(error));
657
+ return null;
658
+ } finally {
659
+ clearTimeout(timer);
660
+ }
661
+ }
662
+ handleMessage(d) {
663
+ const author = d.author;
664
+ if (author?.bot === true) return;
665
+ const text = typeof d.content === "string" ? d.content.trim() : "";
666
+ if (text === "") return;
667
+ const channelId = String(d.channel_id ?? "");
668
+ if (channelId === "") return;
669
+ const guildId = String(d.guild_id ?? "");
670
+ const frame = { channelId, messageId: String(d.id ?? ""), guildId };
671
+ const sink = {
672
+ stream: (f, sid, content, finish) => void this.streamReply(f, sid, content, finish)
673
+ };
674
+ const identity = {
675
+ key: `qq:${channelId}`,
676
+ frame,
677
+ sink,
678
+ chatType: guildId === "" ? "single" : "group"
679
+ };
680
+ console.log("[dsh-message-gateway] qq text", { channelId, text: text.slice(0, 60) });
681
+ this.callbacks.onText(text, identity);
682
+ }
683
+ /** 流式回复:状态合并 + 单 worker——首次被动回复,随后 PATCH 渐进更新(限频)。 */
684
+ async streamReply(frame, streamId, content, finish) {
685
+ const prev = this.state.get(streamId);
686
+ this.state.set(streamId, { content, finish: finish || (prev?.finish ?? false) });
687
+ if (this.working.has(streamId)) return;
688
+ this.working.add(streamId);
689
+ try {
690
+ for (let guard = 0; guard < 200; guard += 1) {
691
+ const current = this.state.get(streamId);
692
+ if (current === void 0) break;
693
+ const text = (current.content === "" ? " " : current.content).slice(0, MSG_LIMIT3);
694
+ const existing = this.streams.get(streamId);
695
+ if (existing === void 0) {
696
+ if (current.content === "" && !current.finish) break;
697
+ const result = await this.rest("POST", `/channels/${frame.channelId}/messages`, {
698
+ content: text,
699
+ msg_type: 0,
700
+ msg_id: frame.messageId
701
+ });
702
+ if (result?.id === void 0) break;
703
+ this.streams.set(streamId, { channelId: frame.channelId, messageId: result.id, lastEdit: Date.now() });
704
+ if (current.finish || this.state.get(streamId).content === current.content) break;
705
+ continue;
706
+ }
707
+ const wait = EDIT_INTERVAL_MS3 - (Date.now() - existing.lastEdit);
708
+ if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
709
+ existing.lastEdit = Date.now();
710
+ await this.rest("PATCH", `/channels/${existing.channelId}/messages/${existing.messageId}`, { content: text });
711
+ if (current.finish || this.state.get(streamId).content === current.content) break;
712
+ }
713
+ } catch (error) {
714
+ console.error("[dsh-message-gateway] qq reply failed", error);
715
+ } finally {
716
+ this.working.delete(streamId);
717
+ }
718
+ }
719
+ /** 停止网关连接。 */
720
+ stop() {
721
+ this.stopped = true;
722
+ this.clearHeartbeat();
723
+ this.streams.clear();
724
+ this.state.clear();
725
+ this.working.clear();
726
+ this.ws?.close();
727
+ this.ws = null;
728
+ this.accessToken = null;
729
+ this.setStatus("idle");
730
+ }
731
+ };
732
+
733
+ // src/host/email-bridge.ts
734
+ import { connect } from "node:net";
735
+ import { connect as tlsConnect } from "node:tls";
736
+ var POLL_MS = 3e4;
737
+ var RETRY_MS = 5e3;
738
+ var MAX_BODY = 12e3;
739
+ var ImapClient = class {
740
+ constructor(host, port, user, pass) {
741
+ this.host = host;
742
+ this.port = port;
743
+ this.user = user;
744
+ this.pass = pass;
745
+ }
746
+ socket = null;
747
+ buffer = "";
748
+ pending = /* @__PURE__ */ new Map();
749
+ untagged = [];
750
+ tagSeq = 0;
751
+ /** 是否走 TLS:993=隐式 TLS;其余端口尝试 STARTTLS(失败则明文)。 */
752
+ get secure() {
753
+ return this.port === 993;
754
+ }
755
+ wire(socket) {
756
+ this.socket = socket;
757
+ socket.setEncoding("utf8");
758
+ socket.on("data", (chunk) => {
759
+ this.buffer += chunk;
760
+ this.process();
761
+ });
762
+ socket.on("error", () => {
763
+ for (const p of this.pending.values()) {
764
+ clearTimeout(p.timer);
765
+ p.reject(new Error("imap connection error"));
766
+ }
767
+ this.pending.clear();
768
+ });
769
+ socket.on("close", () => {
770
+ for (const p of this.pending.values()) {
771
+ clearTimeout(p.timer);
772
+ p.reject(new Error("imap connection closed"));
773
+ }
774
+ this.pending.clear();
775
+ });
776
+ }
777
+ /** 建立连接:读问候 → 可选 STARTTLS 升级。 */
778
+ async connect(timeoutMs = 15e3) {
779
+ if (this.secure) {
780
+ const tls = tlsConnect({ host: this.host, port: this.port, rejectUnauthorized: false });
781
+ this.wire(tls);
782
+ await this.waitGreeting(timeoutMs);
783
+ return;
784
+ }
785
+ const raw = connect({ host: this.host, port: this.port });
786
+ this.wire(raw);
787
+ await this.waitGreeting(timeoutMs);
788
+ try {
789
+ const res = await this.command("STARTTLS", 1e4);
790
+ if (/^a\d+ OK/i.test(res.trim())) {
791
+ raw.removeAllListeners("data");
792
+ const tls = tlsConnect({ socket: raw, rejectUnauthorized: false });
793
+ this.wire(tls);
794
+ await this.waitGreeting(1e4);
795
+ }
796
+ } catch {
797
+ }
798
+ }
799
+ waitGreeting(timeoutMs) {
800
+ return new Promise((resolve, reject) => {
801
+ const timer = setTimeout(() => {
802
+ clearInterval(poll);
803
+ reject(new Error("imap greeting timeout"));
804
+ }, timeoutMs);
805
+ const check = () => {
806
+ const idx = this.untagged.findIndex((l) => l.startsWith("* OK"));
807
+ if (idx !== -1) {
808
+ clearTimeout(timer);
809
+ clearInterval(poll);
810
+ this.untagged.splice(idx, 1);
811
+ resolve();
812
+ }
813
+ };
814
+ const poll = setInterval(check, 20);
815
+ check();
816
+ this.socket?.once("error", () => {
817
+ clearTimeout(timer);
818
+ clearInterval(poll);
819
+ reject(new Error("imap greeting error"));
820
+ });
821
+ });
822
+ }
823
+ /** 发送命令并等待完成标记(tag OK/NO/BAD),返回含未标记响应的全文。 */
824
+ async command(cmd, timeoutMs = 2e4) {
825
+ const tag = `a${++this.tagSeq}`;
826
+ const full = `${tag} ${cmd}\r
827
+ `;
828
+ const existing = this.socket;
829
+ if (existing === null || existing.destroyed) throw new Error("imap not connected");
830
+ return await new Promise((resolve, reject) => {
831
+ const timer = setTimeout(() => {
832
+ this.pending.delete(tag);
833
+ reject(new Error(`imap command timeout: ${cmd.split(" ")[0]}`));
834
+ }, timeoutMs);
835
+ this.pending.set(tag, { resolve, reject, timer });
836
+ existing.write(full);
837
+ });
838
+ }
839
+ /** 解析输入:完整行 + 字面量块。 */
840
+ process() {
841
+ for (; ; ) {
842
+ const literal = this.buffer.match(/^[^\r\n]*\{(\d+)\}\r\n/);
843
+ if (literal !== null) {
844
+ const size = Number(literal[1]);
845
+ if (this.buffer.length < literal[0].length + size) return;
846
+ const block = this.buffer.slice(0, literal[0].length + size);
847
+ this.buffer = this.buffer.slice(literal[0].length + size);
848
+ if (this.buffer.startsWith("\r\n")) this.buffer = this.buffer.slice(2);
849
+ this.dispatch(block);
850
+ continue;
851
+ }
852
+ const line = this.buffer.match(/^[^\r\n]*\r\n/);
853
+ if (line === null) return;
854
+ this.buffer = this.buffer.slice(line[0].length);
855
+ this.dispatch(line[0]);
856
+ }
857
+ }
858
+ dispatch(line) {
859
+ const trimmed = line.trim();
860
+ const tagged = trimmed.match(/^(a\d+) (OK|NO|BAD)(.*)$/);
861
+ if (tagged !== null) {
862
+ const pending = this.pending.get(tagged[1]);
863
+ if (pending !== void 0) {
864
+ clearTimeout(pending.timer);
865
+ this.pending.delete(tagged[1]);
866
+ const collected = [...this.untagged, line].join("");
867
+ this.untagged = [];
868
+ if (tagged[2] === "OK") pending.resolve(collected);
869
+ else pending.reject(new Error(`IMAP ${tagged[2]} ${tagged[3].trim()}`));
870
+ }
871
+ return;
872
+ }
873
+ this.untagged.push(line);
874
+ }
875
+ async login() {
876
+ await this.command(`LOGIN "${this.user}" "${this.pass}"`);
877
+ }
878
+ async select() {
879
+ await this.command("SELECT INBOX");
880
+ }
881
+ /** 未读消息序号列表。 */
882
+ async searchUnseen() {
883
+ const res = await this.command("SEARCH UNSEEN");
884
+ const match = res.match(/\* SEARCH ([\d ]*)/);
885
+ if (match === null) return [];
886
+ return match[1].trim().split(/\s+/).filter((s) => s !== "").map(Number);
887
+ }
888
+ /** FETCH 头部与正文(BODY.PEEK 不置已读)。 */
889
+ async fetchMessage(id) {
890
+ const res = await this.command(
891
+ `FETCH ${id} (UID BODY.PEEK[HEADER.FIELDS (FROM SUBJECT MESSAGE-ID REFERENCES IN-REPLY-TO)] BODY.PEEK[TEXT])`,
892
+ 3e4
893
+ );
894
+ const uid = res.match(/UID (\d+)/)?.[1] ?? String(id);
895
+ const header = literalAt(res, "BODY[HEADER.FIELDS (FROM SUBJECT MESSAGE-ID REFERENCES IN-REPLY-TO)]")?.value ?? "";
896
+ const text = literalAt(res, "BODY[TEXT]")?.value ?? "";
897
+ return { uid, header, text };
898
+ }
899
+ async markSeen(id) {
900
+ await this.command(`STORE ${id} +FLAGS (\\Seen)`);
901
+ }
902
+ close() {
903
+ try {
904
+ this.socket?.end();
905
+ } catch {
906
+ }
907
+ this.socket = null;
908
+ }
909
+ };
910
+ function literalAt(text, marker) {
911
+ const idx = text.indexOf(marker);
912
+ if (idx === -1) return null;
913
+ const sizeMatch = text.slice(idx + marker.length).match(/^ ?\{(\d+)\}\r\n/);
914
+ if (sizeMatch === null) return null;
915
+ const size = Number(sizeMatch[1]);
916
+ const start = idx + marker.length + sizeMatch[0].length;
917
+ return { value: text.slice(start, start + size) };
918
+ }
919
+ var SmtpClient = class {
920
+ constructor(host, port, user, pass, from) {
921
+ this.host = host;
922
+ this.port = port;
923
+ this.user = user;
924
+ this.pass = pass;
925
+ this.from = from;
926
+ }
927
+ onResponse = () => {
928
+ };
929
+ /** 是否隐式 TLS:465 直连 TLS;587/25 走 STARTTLS。 */
930
+ get secure() {
931
+ return this.port === 465;
932
+ }
933
+ /** 发送一封邮件;返回是否成功。 */
934
+ async send(to, subject, body) {
935
+ return await new Promise((resolve) => {
936
+ let socket;
937
+ let step = "greeting";
938
+ let buffer = "";
939
+ const afterTls = (sock, isWrap) => {
940
+ socket = sock;
941
+ if (isWrap) sock.removeAllListeners("data");
942
+ sock.setEncoding("utf8");
943
+ sock.on("data", (chunk) => {
944
+ buffer += chunk;
945
+ drive();
946
+ });
947
+ sock.on("error", () => {
948
+ if (step !== "done") {
949
+ step = "done";
950
+ resolve(false);
951
+ }
952
+ });
953
+ sock.on("close", () => {
954
+ if (step !== "done") {
955
+ step = "done";
956
+ resolve(false);
957
+ }
958
+ });
959
+ };
960
+ const drive = () => {
961
+ if (step === "done") return;
962
+ const parts = buffer.split("\r\n");
963
+ if (parts[parts.length - 1] === "") parts.pop();
964
+ if (parts.length === 0) return;
965
+ const tail = parts[parts.length - 1];
966
+ if (!/^\d{3}( |$)/.test(tail)) return;
967
+ buffer = "";
968
+ const resp = parts[0];
969
+ this.onResponse(resp.slice(0, 3), resp.slice(4), (ok) => resolve(ok));
970
+ };
971
+ const send = (line) => {
972
+ socket.write(`${line}\r
973
+ `);
974
+ };
975
+ this.onResponse = (code, text, done) => {
976
+ switch (step) {
977
+ case "greeting": {
978
+ if (code === "220") {
979
+ step = this.secure ? "ehlo" : "starttls";
980
+ send(`EHLO dsh-message-gateway`);
981
+ } else {
982
+ step = "done";
983
+ done(false);
984
+ }
985
+ break;
986
+ }
987
+ case "starttls": {
988
+ if (code === "250") {
989
+ step = "tls-upgrade";
990
+ send("STARTTLS");
991
+ } else {
992
+ step = "auth";
993
+ send(`AUTH LOGIN`);
994
+ }
995
+ break;
996
+ }
997
+ case "tls-upgrade": {
998
+ if (code === "220") {
999
+ step = "ehlo-tls";
1000
+ const tls = tlsConnect({ socket, rejectUnauthorized: false });
1001
+ afterTls(tls, true);
1002
+ send(`EHLO dsh-message-gateway`);
1003
+ } else {
1004
+ step = "auth";
1005
+ send(`AUTH LOGIN`);
1006
+ }
1007
+ break;
1008
+ }
1009
+ case "ehlo":
1010
+ case "ehlo-tls": {
1011
+ if (code === "250") {
1012
+ step = "auth";
1013
+ send(`AUTH LOGIN`);
1014
+ } else {
1015
+ step = "done";
1016
+ done(false);
1017
+ }
1018
+ break;
1019
+ }
1020
+ case "auth": {
1021
+ if (code === "334") {
1022
+ step = "auth-user";
1023
+ send(Buffer.from(this.user, "utf8").toString("base64"));
1024
+ } else {
1025
+ step = "done";
1026
+ done(false);
1027
+ }
1028
+ break;
1029
+ }
1030
+ case "auth-user": {
1031
+ if (code === "334") {
1032
+ step = "auth-pass";
1033
+ send(Buffer.from(this.pass, "utf8").toString("base64"));
1034
+ } else {
1035
+ step = "done";
1036
+ done(false);
1037
+ }
1038
+ break;
1039
+ }
1040
+ case "auth-pass": {
1041
+ if (code === "235") {
1042
+ step = "mail";
1043
+ send(`MAIL FROM:<${this.from}>`);
1044
+ } else {
1045
+ step = "done";
1046
+ done(false);
1047
+ }
1048
+ break;
1049
+ }
1050
+ case "mail": {
1051
+ if (code === "250") {
1052
+ step = "rcpt";
1053
+ send(`RCPT TO:<${to}>`);
1054
+ } else {
1055
+ step = "done";
1056
+ done(false);
1057
+ }
1058
+ break;
1059
+ }
1060
+ case "rcpt": {
1061
+ if (code === "250") {
1062
+ step = "data";
1063
+ send("DATA");
1064
+ } else {
1065
+ step = "done";
1066
+ done(false);
1067
+ }
1068
+ break;
1069
+ }
1070
+ case "data": {
1071
+ if (code === "354") {
1072
+ step = "content";
1073
+ const headers = [
1074
+ `From: ${this.from}`,
1075
+ `To: ${to}`,
1076
+ `Subject: ${subject}`,
1077
+ "MIME-Version: 1.0",
1078
+ "Content-Type: text/plain; charset=utf-8",
1079
+ "Content-Transfer-Encoding: 8bit"
1080
+ ].join("\r\n");
1081
+ send(`${headers}\r
1082
+ \r
1083
+ ${body}\r
1084
+ .`);
1085
+ } else {
1086
+ step = "done";
1087
+ done(false);
1088
+ }
1089
+ break;
1090
+ }
1091
+ case "content": {
1092
+ if (code === "250") {
1093
+ step = "quit";
1094
+ send("QUIT");
1095
+ done(true);
1096
+ } else {
1097
+ step = "done";
1098
+ done(false);
1099
+ }
1100
+ break;
1101
+ }
1102
+ default:
1103
+ step = "done";
1104
+ done(false);
1105
+ }
1106
+ };
1107
+ const raw = this.secure ? tlsConnect({ host: this.host, port: this.port, rejectUnauthorized: false }) : connect({ host: this.host, port: this.port });
1108
+ afterTls(raw, false);
1109
+ });
1110
+ }
1111
+ };
1112
+ function headerField(header, name) {
1113
+ const match = header.match(new RegExp(`^${name}:(?:[ \\t]*(?:\\r\\n[ \\t]+[^\\r\\n]*)*[ \\t]*[^\\r\\n]*)`, "im"));
1114
+ if (match === null) return "";
1115
+ return match[0].replace(new RegExp(`^${name}:`, "i"), "").replace(/\r\n[ \t]+/g, " ").trim();
1116
+ }
1117
+ function parseAddress(raw) {
1118
+ const angle = raw.match(/<([^<>]+)>/);
1119
+ return (angle?.[1] ?? raw).trim().replace(/^["']|["']$/g, "");
1120
+ }
1121
+ function cleanBody(raw) {
1122
+ let text = raw.replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<br\s*\/?>/gi, "\n").replace(/<\/p>|<\/div>|<\/tr>/gi, "\n").replace(/<[^>]+>/g, "").replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, '"').replace(/&#39;/gi, "'").replace(/\r\n/g, "\n").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
1123
+ if (text.length > MAX_BODY) text = text.slice(0, MAX_BODY);
1124
+ return text;
1125
+ }
1126
+ var EmailBridge = class {
1127
+ constructor(cred, callbacks) {
1128
+ this.cred = cred;
1129
+ this.callbacks = callbacks;
1130
+ }
1131
+ stopped = true;
1132
+ imap = null;
1133
+ seen = /* @__PURE__ */ new Set();
1134
+ status = { state: "idle", detail: "", connectedAt: null };
1135
+ setStatus(state, detail = "") {
1136
+ this.status = { state, detail, connectedAt: state === "connected" ? Date.now() : this.status.connectedAt };
1137
+ this.callbacks.onStatus(this.status);
1138
+ }
1139
+ /** 启动轮询循环。 */
1140
+ start() {
1141
+ if (!this.stopped) return;
1142
+ this.stopped = false;
1143
+ this.setStatus("connecting", "imap");
1144
+ void this.loop();
1145
+ }
1146
+ async loop() {
1147
+ while (!this.stopped) {
1148
+ try {
1149
+ if (this.imap === null) {
1150
+ const imap = new ImapClient(
1151
+ this.cred.imapHost,
1152
+ Number(this.cred.imapPort || "143"),
1153
+ this.cred.imapUser,
1154
+ this.cred.imapPass
1155
+ );
1156
+ await imap.connect();
1157
+ await imap.login();
1158
+ await imap.select();
1159
+ this.imap = imap;
1160
+ this.setStatus("connected", "email");
1161
+ }
1162
+ const ids = await this.imap.searchUnseen();
1163
+ for (const id of ids) {
1164
+ if (this.stopped) break;
1165
+ await this.processMessage(id);
1166
+ }
1167
+ await sleep(POLL_MS);
1168
+ } catch (error) {
1169
+ console.warn("[dsh-message-gateway] email poll error", String(error));
1170
+ this.imap?.close();
1171
+ this.imap = null;
1172
+ this.setStatus("error", "imap error");
1173
+ await sleep(RETRY_MS);
1174
+ }
1175
+ }
1176
+ }
1177
+ async processMessage(id) {
1178
+ if (this.imap === null) return;
1179
+ let fetched;
1180
+ try {
1181
+ fetched = await this.imap.fetchMessage(id);
1182
+ } catch {
1183
+ return;
1184
+ }
1185
+ if (this.seen.has(fetched.uid)) {
1186
+ void this.imap.markSeen(id).catch(() => {
1187
+ });
1188
+ return;
1189
+ }
1190
+ this.seen.add(fetched.uid);
1191
+ const references = headerField(fetched.header, "References").split(/[\s,<>]+/).filter((s) => s.includes("@"));
1192
+ const inReplyTo = parseAddress(headerField(fetched.header, "In-Reply-To"));
1193
+ const messageId = parseAddress(headerField(fetched.header, "Message-ID"));
1194
+ const threadKey = references[0] ?? (inReplyTo !== "" ? inReplyTo : messageId);
1195
+ const from = parseAddress(headerField(fetched.header, "From"));
1196
+ const subject = headerField(fetched.header, "Subject");
1197
+ const text = cleanBody(fetched.text);
1198
+ void this.imap.markSeen(id).catch(() => {
1199
+ });
1200
+ if (from === "" || text.trim() === "") return;
1201
+ const frame = { from, subject, threadKey };
1202
+ const sink = {
1203
+ ack: false,
1204
+ // 邮件不发送「正在处理…」回执
1205
+ stream: (f, _sid, content, finish) => {
1206
+ if (!finish) return;
1207
+ void this.sendReply(f, content);
1208
+ }
1209
+ };
1210
+ const identity = {
1211
+ key: `email:${threadKey === "" ? "default" : threadKey}`,
1212
+ frame,
1213
+ sink,
1214
+ chatType: "single"
1215
+ };
1216
+ console.log("[dsh-message-gateway] email text", { from, subject: subject.slice(0, 40), len: text.length });
1217
+ this.callbacks.onText(text, identity);
1218
+ }
1219
+ async sendReply(frame, content) {
1220
+ try {
1221
+ const smtpHost = this.cred.smtpHost ?? this.cred.imapHost;
1222
+ const smtpPort = Number(this.cred.smtpPort || "465");
1223
+ const smtpUser = this.cred.smtpUser ?? this.cred.imapUser;
1224
+ const smtpPass = this.cred.smtpPass ?? this.cred.imapPass;
1225
+ const smtp = new SmtpClient(smtpHost, smtpPort, smtpUser, smtpPass, smtpUser);
1226
+ const subject = frame.subject.startsWith("Re:") ? frame.subject : `Re: ${frame.subject}`;
1227
+ const ok = await smtp.send(frame.from, subject, content);
1228
+ console.log("[dsh-message-gateway] email reply sent", { to: frame.from, ok });
1229
+ } catch (error) {
1230
+ console.error("[dsh-message-gateway] email reply failed", error);
1231
+ }
1232
+ }
1233
+ /** 停止轮询。 */
1234
+ stop() {
1235
+ this.stopped = true;
1236
+ this.imap?.close();
1237
+ this.imap = null;
1238
+ this.setStatus("idle");
1239
+ }
1240
+ };
1241
+ function sleep(ms) {
1242
+ return new Promise((resolve) => setTimeout(resolve, ms));
1243
+ }
1244
+
1245
+ // src/host/bridge-manager.ts
1246
+ var DEFAULT_MAX_CHAT_AGENTS = 40;
1247
+ var STREAM_PUSH_INTERVAL = 600;
1248
+ var ACK_HEARTBEAT_INTERVAL = 4e3;
1249
+ var BridgeManager = class {
1250
+ constructor(ctx, config) {
1251
+ this.ctx = ctx;
1252
+ this.config = config;
1253
+ }
1254
+ wecom = null;
1255
+ onStatusCallback = null;
1256
+ /** 各聊天在途回复(key = 平台:chatKey)。 */
1257
+ pendingMap = /* @__PURE__ */ new Map();
1258
+ /** Webhook 在途请求(同步等待完整回复;全局单槽位)。 */
1259
+ awaiting = null;
1260
+ /** 各聊天的独立 agent 会话(key = 平台:chatKey;webhook 固定 'webhook')。 */
1261
+ agents = /* @__PURE__ */ new Map();
1262
+ /** 当前语言的文案。 */
1263
+ t(key) {
1264
+ return botText(this.config.botLocale, key);
1265
+ }
1266
+ /** 轮询注入会话的事件流:chunk → 流式推送;assistant/message → 定稿 + HTTP。 */
1267
+ pollPending(key, p, session) {
1268
+ const events = session.events;
1269
+ for (let i = p.cursor; i < events.length; i += 1) {
1270
+ p.cursor = i + 1;
1271
+ const event = events[i];
1272
+ if (event.type === "assistant/chunk") {
1273
+ const chunk = event.data.chunk;
1274
+ if (chunk.type === "text-delta") {
1275
+ p.buffer += chunk.text;
1276
+ this.scheduleStream(p);
1277
+ }
1278
+ continue;
1279
+ }
1280
+ if (event.type === "assistant/message") {
1281
+ const text = extractText(event.data.message);
1282
+ if (text === "" || isToolCallOnly(text)) continue;
1283
+ p.buffer = text;
1284
+ const streamed = p.pushed;
1285
+ console.log("[dsh-message-gateway] assistant done", { key, seq: event.seq, len: p.buffer.length });
1286
+ void this.pushStream(p, true);
1287
+ void this.deliverHttp(p, streamed);
1288
+ this.finishPending(key);
1289
+ return;
1290
+ }
1291
+ if (event.type === "turn/end") {
1292
+ if (p.buffer !== "" && p.pushed) {
1293
+ void this.pushStream(p, true);
1294
+ this.finishPending(key);
1295
+ return;
1296
+ }
1297
+ }
1298
+ }
1299
+ }
1300
+ /** 流式推送:随轮询节奏(每 400ms 一次)全量更新,避免高频发送。 */
1301
+ scheduleStream(p) {
1302
+ void this.pushStream(p, false);
1303
+ }
1304
+ pushStream(p, finish) {
1305
+ if (p.buffer === "" && !finish) return;
1306
+ const now = Date.now();
1307
+ if (!finish && p.lastPush !== 0 && now - p.lastPush < STREAM_PUSH_INTERVAL) return;
1308
+ p.lastPush = now;
1309
+ p.pushed = true;
1310
+ console.log("[dsh-message-gateway] stream push", { finish, len: p.buffer.length });
1311
+ p.sink.stream(p.frame, p.streamId, p.buffer, finish);
1312
+ }
1313
+ /** 经平台 HTTP 定稿通道发送完整回复(幂等;流式已投递时不重复发)。 */
1314
+ async deliverHttp(p, streamed) {
1315
+ if (p.httpDelivered || p.sink.post === void 0 || streamed) return;
1316
+ p.httpDelivered = true;
1317
+ try {
1318
+ await p.sink.post(p.frame, p.buffer);
1319
+ } catch (error) {
1320
+ console.error("[dsh-message-gateway] post delivery failed", error);
1321
+ }
1322
+ }
1323
+ finishPending(key) {
1324
+ const p = this.pendingMap.get(key);
1325
+ if (p === void 0) return;
1326
+ if (p.timer !== null) {
1327
+ clearInterval(p.timer);
1328
+ p.timer = null;
1329
+ }
1330
+ if (p.fallback !== null) {
1331
+ clearTimeout(p.fallback);
1332
+ p.fallback = null;
1333
+ }
1334
+ if (p.heartbeat !== null) {
1335
+ clearInterval(p.heartbeat);
1336
+ p.heartbeat = null;
1337
+ }
1338
+ this.pendingMap.delete(key);
1339
+ if (p.ackSent && !p.pushed) {
1340
+ void p.sink.stream(p.frame, p.streamId, this.t("timeout"), true);
1341
+ }
1342
+ }
1343
+ /** 桥状态变化回调(供路由同步存储)。 */
1344
+ onStatus(fn) {
1345
+ this.onStatusCallback = fn;
1346
+ }
1347
+ /** 创建/获取某聊天的独立 agent:独立会话 + 模型配置(默认跟随部署,可被 botModel 覆盖)。 */
1348
+ async ensureAgentForKey(key) {
1349
+ const existing = this.agents.get(key);
1350
+ if (existing !== void 0) return existing.agent;
1351
+ const override = this.config.botModel;
1352
+ let selection;
1353
+ if (override !== void 0 && override.provider !== "" && override.model !== "") {
1354
+ selection = { provider: override.provider, model: override.model };
1355
+ } else {
1356
+ const defaultModel = this.ctx.get?.("agentDefaultModel");
1357
+ selection = defaultModel?.currentSelection();
1358
+ }
1359
+ let provider = selection?.provider ?? "";
1360
+ let model = selection?.model ?? "";
1361
+ if (provider === "" || model === "") {
1362
+ const root = this.ctx.agents.roots()[0] ?? this.ctx.agents.list()[0];
1363
+ provider = root?.options.provider ?? "";
1364
+ model = root?.options.model ?? "";
1365
+ }
1366
+ if (provider === "" || model === "") {
1367
+ console.warn("[dsh-message-gateway] no model selection available (botModel/agentDefaultModel/roots)");
1368
+ return null;
1369
+ }
1370
+ if (this.agents.size >= (this.config.maxChatAgents > 0 ? this.config.maxChatAgents : DEFAULT_MAX_CHAT_AGENTS)) {
1371
+ const oldestKey = this.agents.keys().next().value;
1372
+ if (oldestKey !== void 0) {
1373
+ const oldest = this.agents.get(oldestKey);
1374
+ this.agents.delete(oldestKey);
1375
+ void oldest?.dispose().catch(() => {
1376
+ });
1377
+ console.log("[dsh-message-gateway] evict oldest chat session", { key: oldestKey });
1378
+ }
1379
+ }
1380
+ try {
1381
+ const sessionId = SessionId(`session-${randomUUID()}`);
1382
+ const handle = await this.ctx.agents.create({
1383
+ sessionId,
1384
+ agentOptions: { provider, model },
1385
+ meta: { cwd: process.cwd(), origin: "subagent" },
1386
+ setup: async (agentCtx) => {
1387
+ const presets = agentCtx.get?.("agentPresets");
1388
+ if (presets !== void 0) {
1389
+ try {
1390
+ await presets.mount(agentCtx);
1391
+ } catch (error) {
1392
+ console.warn("[dsh-message-gateway] agent preset mount skipped", String(error));
1393
+ }
1394
+ }
1395
+ if (selection !== void 0) {
1396
+ installModelSelection(agentCtx, { current: selection, assembled: void 0 });
1397
+ }
1398
+ }
1399
+ });
1400
+ this.agents.set(key, { agent: handle.agent, dispose: () => handle.dispose() });
1401
+ console.log("[dsh-message-gateway] dedicated agent ready", { key, session: handle.agent.session.id, provider, model });
1402
+ return handle.agent;
1403
+ } catch (error) {
1404
+ console.error("[dsh-message-gateway] create agent failed", error);
1405
+ return null;
1406
+ }
1407
+ }
1408
+ /** 主动释放某聊天的会话(对应 Web 的「新会话」;下一条消息自动新建)。 */
1409
+ async resetChat(key) {
1410
+ const entry = this.agents.get(key);
1411
+ if (entry === void 0) return false;
1412
+ this.finishPending(key);
1413
+ this.agents.delete(key);
1414
+ try {
1415
+ await entry.dispose();
1416
+ } catch (error) {
1417
+ console.error("[dsh-message-gateway] reset chat dispose failed", error);
1418
+ }
1419
+ console.log("[dsh-message-gateway] chat session reset", { key });
1420
+ return true;
1421
+ }
1422
+ /** 插件卸载时释放全部聊天会话。 */
1423
+ async dispose() {
1424
+ this.finishAllPending();
1425
+ const entries = [...this.agents.values()];
1426
+ this.agents.clear();
1427
+ await Promise.allSettled(entries.map((entry) => entry.dispose()));
1428
+ this.wecom?.stop();
1429
+ this.wecom = null;
1430
+ }
1431
+ finishAllPending() {
1432
+ for (const key of [...this.pendingMap.keys()]) this.finishPending(key);
1433
+ }
1434
+ /**
1435
+ * 外部平台消息统一入口:命令优先,否则注入该聊天独立 agent 会话,
1436
+ * 回复经 sink 流式回发。所有已打通的平台共用此管线。
1437
+ */
1438
+ async handleExternalMessage(id, rawText) {
1439
+ const text = stripMention(rawText);
1440
+ const reply = (content) => {
1441
+ id.sink.stream(id.frame, `cmd-${Date.now().toString(36)}`, content, true);
1442
+ };
1443
+ try {
1444
+ if (id.chatType === "group" && !this.config.groupReply) return;
1445
+ if (await this.handleCommand(text, id.key, reply)) return;
1446
+ if (this.awaiting !== null) {
1447
+ console.warn("[dsh-message-gateway] busy: webhook in flight, drop message");
1448
+ return;
1449
+ }
1450
+ if (this.pendingMap.has(id.key)) {
1451
+ id.sink.stream(id.frame, `busy-${Date.now().toString(36)}`, this.t("busy"), true);
1452
+ return;
1453
+ }
1454
+ const agent = await this.ensureAgentForKey(id.key);
1455
+ if (agent === null) {
1456
+ console.warn("[dsh-message-gateway] no dedicated agent available");
1457
+ return;
1458
+ }
1459
+ const message = {
1460
+ id: MessageId(`dsh-gateway-${Date.now().toString(36)}`),
1461
+ role: "user",
1462
+ content: [{ type: "text", text }],
1463
+ source: { kind: "plugin", plugin: "dsh-message-gateway", form: "relay" }
1464
+ };
1465
+ const session = agent.session;
1466
+ const p = {
1467
+ frame: id.frame,
1468
+ sink: id.sink,
1469
+ streamId: `gw-${Date.now().toString(36)}`,
1470
+ buffer: "",
1471
+ cursor: session.seq,
1472
+ timer: null,
1473
+ fallback: null,
1474
+ pushed: false,
1475
+ httpDelivered: false,
1476
+ ackSent: false,
1477
+ lastPush: 0,
1478
+ startedAt: Date.now(),
1479
+ heartbeat: null
1480
+ };
1481
+ this.pendingMap.set(id.key, p);
1482
+ if (id.sink.ack !== false) {
1483
+ p.ackSent = true;
1484
+ id.sink.stream(id.frame, p.streamId, this.t("ack"), false);
1485
+ p.heartbeat = setInterval(() => {
1486
+ if (this.pendingMap.get(id.key) !== p || p.pushed) return;
1487
+ const elapsed = Math.round((Date.now() - p.startedAt) / 1e3);
1488
+ id.sink.stream(id.frame, p.streamId, `${this.t("ack")}\uFF08${elapsed}s\uFF09`, false);
1489
+ }, ACK_HEARTBEAT_INTERVAL);
1490
+ p.heartbeat.unref?.();
1491
+ }
1492
+ agent.send(message, "next-turn", true);
1493
+ console.log("[dsh-message-gateway] sent to agent", { key: id.key, text: text.slice(0, 60), baseSeq: p.cursor });
1494
+ p.timer = setInterval(() => {
1495
+ if (this.pendingMap.get(id.key) !== p) return;
1496
+ this.pollPending(id.key, p, session);
1497
+ }, 400);
1498
+ p.fallback = setTimeout(() => {
1499
+ if (this.pendingMap.get(id.key) === p) this.finishPending(id.key);
1500
+ }, 10 * 60 * 1e3);
1501
+ p.fallback.unref?.();
1502
+ } catch (error) {
1503
+ console.error("[dsh-message-gateway] handleExternalMessage failed", error);
1504
+ }
1505
+ }
1506
+ // ==================== 企业微信智能机器人 ====================
1507
+ /** 把一条外部文本消息交给 Webhook 专用 agent 处理,同步等待完整回复(Webhook 通道)。 */
1508
+ async sendAndWait(text, timeoutMs = 9e4) {
1509
+ if (this.pendingMap.size > 0 || this.awaiting !== null) {
1510
+ return { ok: false, reply: "busy: another request is being processed" };
1511
+ }
1512
+ const agent = await this.ensureAgentForKey("webhook");
1513
+ if (agent === null) return { ok: false, reply: "no dedicated agent available" };
1514
+ const session = agent.session;
1515
+ const cursor = session.seq;
1516
+ const message = {
1517
+ id: MessageId(`dsh-gw-webhook-${Date.now().toString(36)}`),
1518
+ role: "user",
1519
+ content: [{ type: "text", text }],
1520
+ source: { kind: "plugin", plugin: "dsh-message-gateway", form: "relay" }
1521
+ };
1522
+ return await new Promise((resolve) => {
1523
+ let settled = false;
1524
+ let timer;
1525
+ let poll;
1526
+ const settle = (ok, reply) => {
1527
+ if (settled) return;
1528
+ settled = true;
1529
+ clearTimeout(timer);
1530
+ clearInterval(poll);
1531
+ this.awaiting = null;
1532
+ resolve({ ok, reply });
1533
+ };
1534
+ timer = setTimeout(() => settle(false, "timeout waiting for reply"), timeoutMs);
1535
+ poll = setInterval(() => {
1536
+ if (this.awaiting === null) {
1537
+ clearInterval(poll);
1538
+ return;
1539
+ }
1540
+ const events = session.events;
1541
+ for (let i = cursor; i < events.length; i += 1) {
1542
+ const event = events[i];
1543
+ if (event.type === "assistant/message") {
1544
+ const reply = extractText(event.data.message);
1545
+ if (reply !== "" && !isToolCallOnly(reply)) {
1546
+ settle(true, reply);
1547
+ return;
1548
+ }
1549
+ }
1550
+ }
1551
+ }, 400);
1552
+ this.awaiting = { resolve: (reply) => settle(true, reply) };
1553
+ try {
1554
+ agent.send(message, "next-turn", true);
1555
+ console.log("[dsh-message-gateway] webhook sent to agent", { text: text.slice(0, 60), baseSeq: cursor });
1556
+ } catch (error) {
1557
+ console.error("[dsh-message-gateway] webhook send failed", error);
1558
+ settle(false, "send failed");
1559
+ }
1560
+ });
1561
+ }
1562
+ /** 启动企业微信桥(凭据变化时先停旧桥)。 */
1563
+ startWecom(cred) {
1564
+ this.wecom?.stop();
1565
+ const bridge = new WecomBridge(cred, {
1566
+ onStatus: (status) => this.onStatusCallback?.(status),
1567
+ onText: (rawText, frame) => {
1568
+ const body = frame.body ?? {};
1569
+ const chattype = body.chattype ?? "single";
1570
+ const userid = body.from?.userid ?? "";
1571
+ const chatid = body.chatid ?? "";
1572
+ const key = chatid !== "" ? `wecom:group:${chatid}` : `wecom:user:${userid}`;
1573
+ const sink = {
1574
+ stream: (f, sid, content, finish) => void this.wecom?.streamReply(f, sid, content, finish)
1575
+ // 企业微信走单一流式消息(ack → 内容 → 定稿同一条消息就地更新);
1576
+ // 不再叠加 response_url 投递,避免出现重复消息。
1577
+ };
1578
+ void this.handleExternalMessage({ key, frame, sink, chatType: chattype === "group" ? "group" : "single" }, rawText);
1579
+ },
1580
+ onEnter: (frame) => {
1581
+ const userid = frame.body?.from?.userid ?? "";
1582
+ console.log("[dsh-message-gateway] enter chat", { userid });
1583
+ void this.wecom?.welcome(frame, this.t("welcome"));
1584
+ }
1585
+ });
1586
+ this.wecom = bridge;
1587
+ bridge.start();
1588
+ }
1589
+ /** 停止企业微信桥(保留各聊天会话上下文)。 */
1590
+ stopWecom() {
1591
+ this.finishAllPending();
1592
+ this.wecom?.stop();
1593
+ this.wecom = null;
1594
+ }
1595
+ /** 当前桥状态(供路由展示)。 */
1596
+ wecomStatus() {
1597
+ return this.wecom?.status ?? { state: "idle", detail: "", connectedAt: null };
1598
+ }
1599
+ /** 当前活跃聊天会话数(供状态展示)。 */
1600
+ chatCount() {
1601
+ return this.agents.size;
1602
+ }
1603
+ /** 主动向会话发送 markdown 消息(单聊=userid,群聊=群 ID)。 */
1604
+ async sendToChat(chatid, content) {
1605
+ if (this.wecom === null) return false;
1606
+ return this.wecom.sendMessage(chatid, content);
1607
+ }
1608
+ // ==================== Telegram / Discord / QQ / Email ====================
1609
+ telegram = null;
1610
+ discord = null;
1611
+ qq = null;
1612
+ email = null;
1613
+ /** 启动 Telegram 桥(长轮询)。 */
1614
+ startTelegram(cred) {
1615
+ this.telegram?.stop();
1616
+ const bridge = new TelegramBridge(cred.token ?? "", {
1617
+ onStatus: (status) => this.onStatusCallback?.(status),
1618
+ onText: (text, identity) => void this.handleExternalMessage(identity, text)
1619
+ });
1620
+ this.telegram = bridge;
1621
+ bridge.start();
1622
+ }
1623
+ /** 停止 Telegram 桥。 */
1624
+ stopTelegram() {
1625
+ this.telegram?.stop();
1626
+ this.telegram = null;
1627
+ }
1628
+ /** 启动 Discord 桥(WebSocket 网关)。 */
1629
+ startDiscord(cred) {
1630
+ this.discord?.stop();
1631
+ const bridge = new DiscordBridge(cred.token ?? "", {
1632
+ onStatus: (status) => this.onStatusCallback?.(status),
1633
+ onText: (text, identity) => void this.handleExternalMessage(identity, text)
1634
+ });
1635
+ this.discord = bridge;
1636
+ bridge.start();
1637
+ }
1638
+ /** 停止 Discord 桥。 */
1639
+ stopDiscord() {
1640
+ this.discord?.stop();
1641
+ this.discord = null;
1642
+ }
1643
+ /** 启动 QQ 桥(access_token + 网关)。 */
1644
+ startQQ(cred) {
1645
+ this.qq?.stop();
1646
+ const bridge = new QQBridge(cred.appId ?? "", cred.secret ?? "", {
1647
+ onStatus: (status) => this.onStatusCallback?.(status),
1648
+ onText: (text, identity) => void this.handleExternalMessage(identity, text)
1649
+ });
1650
+ this.qq = bridge;
1651
+ bridge.start();
1652
+ }
1653
+ /** 停止 QQ 桥。 */
1654
+ stopQQ() {
1655
+ this.qq?.stop();
1656
+ this.qq = null;
1657
+ }
1658
+ /** 启动 Email 桥(IMAP 轮询 + SMTP 回复)。 */
1659
+ startEmail(cred) {
1660
+ this.email?.stop();
1661
+ const emailCred = {
1662
+ imapHost: cred.imapHost ?? "",
1663
+ imapPort: cred.imapPort ?? "143",
1664
+ imapUser: cred.imapUser ?? "",
1665
+ imapPass: cred.imapPass ?? "",
1666
+ smtpHost: cred.smtpHost ?? void 0,
1667
+ smtpPort: cred.smtpPort ?? void 0,
1668
+ smtpUser: cred.smtpUser ?? void 0,
1669
+ smtpPass: cred.smtpPass ?? void 0
1670
+ };
1671
+ const bridge = new EmailBridge(emailCred, {
1672
+ onStatus: (status) => this.onStatusCallback?.(status),
1673
+ onText: (text, identity) => void this.handleExternalMessage(identity, text)
1674
+ });
1675
+ this.email = bridge;
1676
+ bridge.start();
1677
+ }
1678
+ /** 停止 Email 桥。 */
1679
+ stopEmail() {
1680
+ this.email?.stop();
1681
+ this.email = null;
1682
+ }
1683
+ /** 任意桥接平台的状态(telegram/discord/qq/email)。 */
1684
+ bridgeStatus(id) {
1685
+ if (id === "telegram") return this.telegram?.status ?? { state: "idle", detail: "", connectedAt: null };
1686
+ if (id === "discord") return this.discord?.status ?? { state: "idle", detail: "", connectedAt: null };
1687
+ if (id === "qq") return this.qq?.status ?? { state: "idle", detail: "", connectedAt: null };
1688
+ if (id === "email") return this.email?.status ?? { state: "idle", detail: "", connectedAt: null };
1689
+ return { state: "idle", detail: "", connectedAt: null };
1690
+ }
1691
+ /** 将桥状态并入存储状态。 */
1692
+ mergeStatus(stored, id = "wecom-aibot") {
1693
+ const live = id === "wecom-aibot" ? this.wecomStatus() : this.bridgeStatus(id);
1694
+ if (live.state === "connected") {
1695
+ return { state: "connected", detail: live.detail, testedAt: live.connectedAt ?? stored?.testedAt ?? null };
1696
+ }
1697
+ if (live.state === "error") {
1698
+ return { state: "error", detail: live.detail, testedAt: stored?.testedAt ?? null };
1699
+ }
1700
+ if (live.state === "connecting") {
1701
+ return { state: stored?.state ?? "none", detail: "\u8FDE\u63A5\u4E2D\u2026", testedAt: stored?.testedAt ?? null };
1702
+ }
1703
+ return stored ?? { state: "none", detail: "", testedAt: null };
1704
+ }
1705
+ /** 斜杠命令 / 关键词命令;已处理返回 true(不经 agent)。 */
1706
+ async handleCommand(text, key, reply) {
1707
+ if (text === "/help" || text === "\u5E2E\u52A9" || text === "\u83DC\u5355" || text === "\uFF1F" || text === "?") {
1708
+ reply(this.t("help"));
1709
+ return true;
1710
+ }
1711
+ if (text === "/time" || text === "\u65F6\u95F4") {
1712
+ reply(`${this.t("timePrefix")} ${nowInShanghai()}\uFF08Asia/Shanghai\uFF09`);
1713
+ return true;
1714
+ }
1715
+ if (text === "/new" || text === "/clear" || text === "\u65B0\u4F1A\u8BDD" || text === "\u6E05\u7A7A\u4F1A\u8BDD") {
1716
+ const reset = await this.resetChat(key);
1717
+ reply(reset ? this.t("newOk") : this.t("newIdle"));
1718
+ return true;
1719
+ }
1720
+ if (text === "/status" || text === "\u72B6\u6001") {
1721
+ const dot = this.ctx.agents.list().length > 0 ? this.t("statusAvailable") : this.t("statusUnavailable");
1722
+ reply(
1723
+ `${this.t("statusTitle")}
1724
+ - ${this.t("statusChats")}: ${this.chatCount()} \u4E2A
1725
+ - ${this.t("statusAgent")}: ${dot}
1726
+ - ${this.t("statusTime")}: ${nowInShanghai()}`
1727
+ );
1728
+ return true;
1729
+ }
1730
+ return false;
1731
+ }
1732
+ };
1733
+ function extractText(message) {
1734
+ return message.content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text ?? "").join("\n");
1735
+ }
1736
+ function isToolCallOnly(text) {
1737
+ const trimmed = text.trim();
1738
+ if (trimmed === "") return false;
1739
+ if (trimmed.startsWith("<tool_calls>") && trimmed.endsWith("</tool_calls>")) return true;
1740
+ return /^<tool_calls>[\s\S]*<\/tool_calls>\s*$/.test(trimmed);
1741
+ }
1742
+ function stripMention(content) {
1743
+ const text = content.trim();
1744
+ if (text.startsWith("@")) {
1745
+ const space = text.indexOf(" ");
1746
+ if (space !== -1 && space <= 64) return text.slice(space + 1).trim();
1747
+ }
1748
+ return text;
1749
+ }
1750
+ function nowInShanghai() {
1751
+ return new Intl.DateTimeFormat("zh-CN", {
1752
+ timeZone: "Asia/Shanghai",
1753
+ year: "numeric",
1754
+ month: "2-digit",
1755
+ day: "2-digit",
1756
+ hour: "2-digit",
1757
+ minute: "2-digit",
1758
+ second: "2-digit",
1759
+ hour12: false
1760
+ }).format(/* @__PURE__ */ new Date());
1761
+ }
1762
+
1763
+ // src/host/gateway-store.ts
1764
+ import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
1765
+ import { homedir } from "node:os";
1766
+ import { join } from "node:path";
1767
+ var FILE = join(homedir(), ".dsh", "gateway.json");
1768
+ async function loadStore() {
1769
+ try {
1770
+ const text = await readFile(FILE, "utf8");
1771
+ const parsed = JSON.parse(text);
1772
+ return {
1773
+ platforms: parsed.platforms ?? {},
1774
+ statuses: parsed.statuses ?? {}
1775
+ };
1776
+ } catch {
1777
+ return { platforms: {}, statuses: {} };
1778
+ }
1779
+ }
1780
+ async function saveStore(data) {
1781
+ await mkdir(join(homedir(), ".dsh"), { recursive: true });
1782
+ const tmp = `${FILE}.tmp`;
1783
+ await writeFile(tmp, JSON.stringify(data, null, 2), { mode: 384 });
1784
+ await chmod(tmp, 384);
1785
+ await rename(tmp, FILE);
1786
+ }
1787
+
1788
+ // src/host/routes.ts
1789
+ import { createHmac, timingSafeEqual } from "node:crypto";
1790
+
1791
+ // src/host/platforms.ts
1792
+ import { connect as connect2 } from "node:net";
1793
+ import AiBot2 from "@wecom/aibot-node-sdk";
1794
+ var PLATFORMS = [
1795
+ {
1796
+ id: "telegram",
1797
+ nameKey: "platform.telegram",
1798
+ icon: "\u2708\uFE0F",
1799
+ testable: true,
1800
+ fields: [{ key: "token", labelKey: "field.token", placeholderKey: "field.token.ph", kind: "secret" }]
1801
+ },
1802
+ {
1803
+ id: "discord",
1804
+ nameKey: "platform.discord",
1805
+ icon: "\u{1F3AE}",
1806
+ testable: true,
1807
+ fields: [{ key: "token", labelKey: "field.token", placeholderKey: "field.token.ph", kind: "secret" }]
1808
+ },
1809
+ {
1810
+ id: "qq",
1811
+ nameKey: "platform.qq",
1812
+ icon: "\u{1F4AC}",
1813
+ testable: true,
1814
+ fields: [
1815
+ { key: "appId", labelKey: "field.appId", kind: "text" },
1816
+ { key: "secret", labelKey: "field.secret", placeholderKey: "field.secret.ph", kind: "secret" }
1817
+ ]
1818
+ },
1819
+ {
1820
+ id: "wecom",
1821
+ nameKey: "platform.wecom",
1822
+ icon: "\u{1F3E2}",
1823
+ testable: true,
1824
+ hintKey: "platform.wecom.hint",
1825
+ fields: [
1826
+ { key: "corpId", labelKey: "field.corpId", kind: "text" },
1827
+ { key: "agentId", labelKey: "field.agentId", kind: "text" },
1828
+ { key: "secret", labelKey: "field.secret", placeholderKey: "field.secret.ph", kind: "secret" },
1829
+ { key: "token", labelKey: "field.callbackToken", kind: "text" },
1830
+ { key: "encodingAESKey", labelKey: "field.encodingAESKey", placeholderKey: "field.secret.ph", kind: "secret" }
1831
+ ]
1832
+ },
1833
+ {
1834
+ id: "wecom-aibot",
1835
+ nameKey: "platform.wecomAibot",
1836
+ icon: "\u{1F916}",
1837
+ testable: true,
1838
+ hintKey: "platform.wecomAibot.hint",
1839
+ fields: [
1840
+ { key: "botId", labelKey: "field.botId", kind: "text" },
1841
+ { key: "secret", labelKey: "field.secret", placeholderKey: "field.secret.ph", kind: "secret" }
1842
+ ]
1843
+ },
1844
+ {
1845
+ id: "wechat",
1846
+ nameKey: "platform.wechat",
1847
+ icon: "\u{1F49A}",
1848
+ testable: false,
1849
+ hintKey: "platform.wechat.hint",
1850
+ fields: [
1851
+ { key: "gatewayUrl", labelKey: "field.gatewayUrl", placeholderKey: "field.gatewayUrl.ph", kind: "text" },
1852
+ { key: "token", labelKey: "field.token", placeholderKey: "field.secret.ph", kind: "secret" }
1853
+ ]
1854
+ },
1855
+ {
1856
+ id: "wechat-mp",
1857
+ nameKey: "platform.wechatMp",
1858
+ icon: "\u{1F4F0}",
1859
+ testable: true,
1860
+ hintKey: "platform.wechatMp.hint",
1861
+ fields: [
1862
+ { key: "appId", labelKey: "field.appId", kind: "text" },
1863
+ { key: "secret", labelKey: "field.secret", placeholderKey: "field.secret.ph", kind: "secret" },
1864
+ { key: "token", labelKey: "field.callbackToken", kind: "text" }
1865
+ ]
1866
+ },
1867
+ {
1868
+ id: "whatsapp",
1869
+ nameKey: "platform.whatsapp",
1870
+ icon: "\u{1F7E2}",
1871
+ testable: true,
1872
+ hintKey: "platform.whatsapp.hint",
1873
+ fields: [
1874
+ { key: "token", labelKey: "field.token", placeholderKey: "field.token.ph", kind: "secret" },
1875
+ { key: "phoneId", labelKey: "field.phoneId", kind: "text" }
1876
+ ]
1877
+ },
1878
+ {
1879
+ id: "email",
1880
+ nameKey: "platform.email",
1881
+ icon: "\u{1F4E7}",
1882
+ testable: true,
1883
+ hintKey: "platform.email.hint",
1884
+ fields: [
1885
+ { key: "imapHost", labelKey: "field.imapHost", kind: "text" },
1886
+ { key: "imapPort", labelKey: "field.imapPort", kind: "number" },
1887
+ { key: "imapUser", labelKey: "field.imapUser", kind: "text" },
1888
+ { key: "imapPass", labelKey: "field.imapPass", placeholderKey: "field.secret.ph", kind: "secret" },
1889
+ { key: "smtpHost", labelKey: "field.smtpHost", kind: "text" },
1890
+ { key: "smtpPort", labelKey: "field.smtpPort", kind: "number" },
1891
+ { key: "smtpUser", labelKey: "field.smtpUser", kind: "text" },
1892
+ { key: "smtpPass", labelKey: "field.smtpPass", placeholderKey: "field.secret.ph", kind: "secret" }
1893
+ ]
1894
+ },
1895
+ {
1896
+ id: "webhooks",
1897
+ nameKey: "platform.webhooks",
1898
+ icon: "\u{1FA9D}",
1899
+ testable: false,
1900
+ hintKey: "platform.webhooks.hint",
1901
+ fields: [{ key: "secret", labelKey: "field.webhookSecret", placeholderKey: "field.secret.ph", kind: "secret" }]
1902
+ }
1903
+ ];
1904
+ function platformDef(id) {
1905
+ return PLATFORMS.find((p) => p.id === id);
1906
+ }
1907
+ async function httpJson(url, init) {
1908
+ const controller = new AbortController();
1909
+ const timer = setTimeout(() => controller.abort(), 12e3);
1910
+ try {
1911
+ const response = await fetch(url, { ...init, signal: controller.signal });
1912
+ let body = null;
1913
+ try {
1914
+ body = await response.json();
1915
+ } catch {
1916
+ }
1917
+ return { status: response.status, body };
1918
+ } finally {
1919
+ clearTimeout(timer);
1920
+ }
1921
+ }
1922
+ function tcpBanner(host, port, timeoutMs = 8e3) {
1923
+ return new Promise((resolve) => {
1924
+ const socket = connect2({ host, port });
1925
+ const timer = setTimeout(() => {
1926
+ socket.destroy();
1927
+ resolve("");
1928
+ }, timeoutMs);
1929
+ socket.setEncoding("utf8");
1930
+ socket.on("connect", () => {
1931
+ });
1932
+ socket.once("data", (chunk) => {
1933
+ clearTimeout(timer);
1934
+ socket.destroy();
1935
+ resolve(String(chunk).trim().slice(0, 120));
1936
+ });
1937
+ socket.on("error", () => {
1938
+ clearTimeout(timer);
1939
+ resolve("");
1940
+ });
1941
+ });
1942
+ }
1943
+ async function testPlatform(id, cred) {
1944
+ switch (id) {
1945
+ case "telegram": {
1946
+ const { status, body } = await httpJson(`https://api.telegram.org/bot${cred.token ?? ""}/getMe`);
1947
+ const r = body;
1948
+ if (status === 200 && r.ok === true && r.result !== void 0) {
1949
+ return { ok: true, detail: `@${r.result.username ?? ""}` };
1950
+ }
1951
+ return { ok: false, detail: r.description ?? `HTTP ${status}` };
1952
+ }
1953
+ case "discord": {
1954
+ const { status, body } = await httpJson("https://discord.com/api/v10/users/@me", {
1955
+ headers: { authorization: `Bot ${cred.token ?? ""}` }
1956
+ });
1957
+ const r = body;
1958
+ if (status === 200) return { ok: true, detail: r.username ?? "ok" };
1959
+ return { ok: false, detail: r.message ?? `HTTP ${status}` };
1960
+ }
1961
+ case "qq": {
1962
+ const { status, body } = await httpJson("https://bots.qq.com/app/getAppAccessToken", {
1963
+ method: "POST",
1964
+ headers: { "content-type": "application/json" },
1965
+ body: JSON.stringify({ appId: cred.appId ?? "", clientSecret: cred.secret ?? "" })
1966
+ });
1967
+ const r = body;
1968
+ if (status === 200 && r.access_token !== void 0) return { ok: true, detail: `appId ${cred.appId}` };
1969
+ return { ok: false, detail: r.message ?? `HTTP ${status}` };
1970
+ }
1971
+ case "wecom-aibot": {
1972
+ const client = new AiBot2.WSClient({ botId: cred.botId ?? "", secret: cred.secret ?? "" });
1973
+ return await new Promise((resolve) => {
1974
+ const timer = setTimeout(() => {
1975
+ client.disconnect();
1976
+ resolve({ ok: false, detail: "\u8FDE\u63A5\u8D85\u65F6" });
1977
+ }, 12e3);
1978
+ client.on("authenticated", () => {
1979
+ clearTimeout(timer);
1980
+ client.disconnect();
1981
+ resolve({ ok: true, detail: `botId ${cred.botId ?? ""}` });
1982
+ });
1983
+ client.on("error", (err) => {
1984
+ clearTimeout(timer);
1985
+ client.disconnect();
1986
+ resolve({ ok: false, detail: err?.message ?? "\u8FDE\u63A5\u9519\u8BEF" });
1987
+ });
1988
+ client.connect();
1989
+ });
1990
+ }
1991
+ case "wecom": {
1992
+ const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${encodeURIComponent(cred.corpId ?? "")}&corpsecret=${encodeURIComponent(cred.secret ?? "")}`;
1993
+ const { body } = await httpJson(url);
1994
+ const r = body;
1995
+ if (r.errcode === 0 && r.access_token !== void 0) return { ok: true, detail: `corpId ${cred.corpId}` };
1996
+ return { ok: false, detail: r.errmsg ?? "\u672A\u77E5\u9519\u8BEF" };
1997
+ }
1998
+ case "wechat-mp": {
1999
+ const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${encodeURIComponent(cred.appId ?? "")}&secret=${encodeURIComponent(cred.secret ?? "")}`;
2000
+ const { body } = await httpJson(url);
2001
+ const r = body;
2002
+ if (r.access_token !== void 0) return { ok: true, detail: `appId ${cred.appId}` };
2003
+ return { ok: false, detail: r.errmsg ?? "\u672A\u77E5\u9519\u8BEF" };
2004
+ }
2005
+ case "whatsapp": {
2006
+ const url = `https://graph.facebook.com/v20.0/${encodeURIComponent(cred.phoneId ?? "")}?access_token=${encodeURIComponent(cred.token ?? "")}`;
2007
+ const { status, body } = await httpJson(url);
2008
+ const r = body;
2009
+ if (status === 200) return { ok: true, detail: r.name ?? `phoneId ${cred.phoneId}` };
2010
+ return { ok: false, detail: r.error?.message ?? `HTTP ${status}` };
2011
+ }
2012
+ case "email": {
2013
+ const port = Number(cred.imapPort ?? "143");
2014
+ const banner = await tcpBanner(cred.imapHost ?? "", port);
2015
+ if (banner !== "" && /ok|ready|imap/i.test(banner)) {
2016
+ return { ok: true, detail: banner };
2017
+ }
2018
+ return { ok: false, detail: banner === "" ? `\u65E0\u6CD5\u8FDE\u63A5 ${cred.imapHost}:${port}` : banner };
2019
+ }
2020
+ default:
2021
+ return { ok: true, detail: "configured" };
2022
+ }
2023
+ }
2024
+
2025
+ // src/host/callback-bridges.ts
2026
+ import { createHash, createDecipheriv, createCipheriv, randomBytes } from "node:crypto";
2027
+ var TOKEN_TTL_MS = 7e6;
2028
+ var tokenCache = /* @__PURE__ */ new Map();
2029
+ function cachedToken(key) {
2030
+ const entry = tokenCache.get(key);
2031
+ if (entry === void 0 || entry.expiresAt <= Date.now()) return null;
2032
+ return entry.token;
2033
+ }
2034
+ function setCachedToken(key, token) {
2035
+ tokenCache.set(key, { token, expiresAt: Date.now() + TOKEN_TTL_MS });
2036
+ }
2037
+ function sha1Sorted(parts) {
2038
+ const sorted = [...parts].sort();
2039
+ return createHash("sha1").update(sorted.join("")).digest("hex");
2040
+ }
2041
+ function xmlField(xml, name) {
2042
+ const match = xml.match(new RegExp(`<${name}>(?:<!\\[CDATA\\[)?([\\s\\S]*?)(?:\\]\\]>)?<\\/${name}>`));
2043
+ return match === null ? "" : match[1].trim();
2044
+ }
2045
+ function xmlEncrypt(xml) {
2046
+ return xmlField(xml, "Encrypt");
2047
+ }
2048
+ function unpad(data) {
2049
+ const pad2 = data[data.length - 1];
2050
+ if (pad2 < 1 || pad2 > 32) return data;
2051
+ return data.subarray(0, data.length - pad2);
2052
+ }
2053
+ function pad(data, blockSize = 32) {
2054
+ const len = blockSize - data.length % blockSize;
2055
+ return Buffer.concat([data, Buffer.alloc(len, len)]);
2056
+ }
2057
+ function buildKey(encodingAESKey) {
2058
+ return Buffer.from(`${encodingAESKey}=`, "base64");
2059
+ }
2060
+ var WecomAppBridge = class {
2061
+ constructor(corpId, agentId, secret, token, encodingAESKey) {
2062
+ this.corpId = corpId;
2063
+ this.agentId = agentId;
2064
+ this.secret = secret;
2065
+ this.token = token;
2066
+ this.encodingAESKey = encodingAESKey;
2067
+ }
2068
+ /** 校验回调签名(token + timestamp + nonce + encrypt 排序拼接 SHA1)。 */
2069
+ verifySignature(msgSignature, timestamp, nonce, encrypt) {
2070
+ if (this.token === "" || msgSignature === "" || timestamp === "" || nonce === "" || encrypt === "") return false;
2071
+ const expected = sha1Sorted([this.token, timestamp, nonce, encrypt]);
2072
+ return expected === msgSignature.toLowerCase();
2073
+ }
2074
+ /** 解密回调密文 → { message, receiveId }(16B 随机 + 4B 长度 + 消息 + corpId)。 */
2075
+ decrypt(encrypt) {
2076
+ const key = buildKey(this.encodingAESKey);
2077
+ const decipher = createDecipheriv("aes-256-cbc", key, key.subarray(0, 16));
2078
+ const plain = unpad(Buffer.concat([decipher.update(Buffer.from(encrypt, "base64")), decipher.final()]));
2079
+ const msgLen = plain.readUInt32BE(16);
2080
+ return {
2081
+ message: plain.subarray(20, 20 + msgLen).toString("utf8"),
2082
+ receiveId: plain.subarray(20 + msgLen).toString("utf8")
2083
+ };
2084
+ }
2085
+ /** 加密(被动回复 / 测试往返用)。 */
2086
+ encrypt(message) {
2087
+ const key = buildKey(this.encodingAESKey);
2088
+ const payload = Buffer.concat([
2089
+ randomBytes(16),
2090
+ (() => {
2091
+ const b = Buffer.alloc(4);
2092
+ b.writeUInt32BE(Buffer.byteLength(message));
2093
+ return b;
2094
+ })(),
2095
+ Buffer.from(message, "utf8"),
2096
+ Buffer.from(this.corpId, "utf8")
2097
+ ]);
2098
+ const cipher = createCipheriv("aes-256-cbc", key, key.subarray(0, 16));
2099
+ return Buffer.concat([cipher.update(pad(payload)), cipher.final()]).toString("base64");
2100
+ }
2101
+ /** 解析解密后的消息 XML → { from, text }。 */
2102
+ parseMessage(xml) {
2103
+ return { from: xmlField(xml, "FromUserName"), text: xmlField(xml, "Content") };
2104
+ }
2105
+ /** 发送文本到用户(企业微信应用消息 API;文本上限 2048 字节)。 */
2106
+ async sendText(userId, content) {
2107
+ const token = await this.accessToken();
2108
+ if (token === null) return false;
2109
+ const body = { touser: userId, msgtype: "text", agentid: Number(this.agentId) || 0, text: { content: content.slice(0, 2e3) } };
2110
+ const result = await postJson(
2111
+ `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${encodeURIComponent(token)}`,
2112
+ body
2113
+ );
2114
+ if (result === null) return false;
2115
+ if (result.errcode === 0) return true;
2116
+ if (result.errcode === 42001 || result.errcode === 40014) {
2117
+ tokenCache.delete(`wecom:${this.corpId}`);
2118
+ const retry = await this.accessToken();
2119
+ if (retry === null) return false;
2120
+ const again = await postJson(
2121
+ `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${encodeURIComponent(retry)}`,
2122
+ body
2123
+ );
2124
+ return again?.errcode === 0;
2125
+ }
2126
+ console.warn("[dsh-message-gateway] wecom-app send failed", result.errmsg ?? result.errcode);
2127
+ return false;
2128
+ }
2129
+ async accessToken() {
2130
+ const cacheKey = `wecom:${this.corpId}`;
2131
+ const cached = cachedToken(cacheKey);
2132
+ if (cached !== null) return cached;
2133
+ const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${encodeURIComponent(this.corpId)}&corpsecret=${encodeURIComponent(this.secret)}`;
2134
+ const result = await getJson(url);
2135
+ if (result !== null && result.errcode === 0 && result.access_token !== void 0) {
2136
+ setCachedToken(cacheKey, result.access_token);
2137
+ return result.access_token;
2138
+ }
2139
+ return null;
2140
+ }
2141
+ };
2142
+ var WechatMpBridge = class {
2143
+ constructor(appId, secret, token) {
2144
+ this.appId = appId;
2145
+ this.secret = secret;
2146
+ this.token = token;
2147
+ }
2148
+ /** 校验回调签名(token + timestamp + nonce 排序拼接 SHA1)。 */
2149
+ verifySignature(signature, timestamp, nonce) {
2150
+ if (this.token === "" || signature === "" || timestamp === "" || nonce === "") return false;
2151
+ return sha1Sorted([this.token, timestamp, nonce]) === signature.toLowerCase();
2152
+ }
2153
+ /** 解析消息 XML → { from, to, text, msgType }。 */
2154
+ parseMessage(xml) {
2155
+ return {
2156
+ from: xmlField(xml, "FromUserName"),
2157
+ to: xmlField(xml, "ToUserName"),
2158
+ text: xmlField(xml, "Content"),
2159
+ msgType: xmlField(xml, "MsgType")
2160
+ };
2161
+ }
2162
+ /** 发送文本到用户(公众号客服消息 API)。 */
2163
+ async sendText(openId, content) {
2164
+ const token = await this.accessToken();
2165
+ if (token === null) return false;
2166
+ const body = { touser: openId, msgtype: "text", text: { content: content.slice(0, 2e3) } };
2167
+ const result = await postJson(
2168
+ `https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${encodeURIComponent(token)}`,
2169
+ body
2170
+ );
2171
+ if (result !== null && result.errcode === 0) return true;
2172
+ if (result !== null && (result.errcode === 40001 || result.errcode === 42001)) {
2173
+ tokenCache.delete(`mp:${this.appId}`);
2174
+ const retry = await this.accessToken();
2175
+ if (retry === null) return false;
2176
+ const again = await postJson(
2177
+ `https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${encodeURIComponent(retry)}`,
2178
+ body
2179
+ );
2180
+ return again?.errcode === 0;
2181
+ }
2182
+ console.warn("[dsh-message-gateway] wechat-mp send failed", result?.errmsg ?? "unknown");
2183
+ return false;
2184
+ }
2185
+ async accessToken() {
2186
+ const cacheKey = `mp:${this.appId}`;
2187
+ const cached = cachedToken(cacheKey);
2188
+ if (cached !== null) return cached;
2189
+ const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${encodeURIComponent(this.appId)}&secret=${encodeURIComponent(this.secret)}`;
2190
+ const result = await getJson(url);
2191
+ if (result !== null && result.access_token !== void 0) {
2192
+ setCachedToken(cacheKey, result.access_token);
2193
+ return result.access_token;
2194
+ }
2195
+ return null;
2196
+ }
2197
+ };
2198
+ var WhatsappBridge = class {
2199
+ constructor(token, phoneId) {
2200
+ this.token = token;
2201
+ this.phoneId = phoneId;
2202
+ }
2203
+ /** Webhook 验证:hub.mode=subscribe 且 hub.verify_token 匹配 → 返回 challenge。 */
2204
+ verifyChallenge(params) {
2205
+ if (params.mode !== "subscribe") return null;
2206
+ if (params.verify_token === void 0 || params.verify_token === "") return null;
2207
+ const stored = this.token;
2208
+ if (stored === "") return null;
2209
+ return params.verify_token === stored ? params.challenge ?? null : null;
2210
+ }
2211
+ /** 从 Webhook 负载提取 { from, text }。 */
2212
+ parseWebhook(body) {
2213
+ if (typeof body !== "object" || body === null) return null;
2214
+ const entry = body.entry;
2215
+ const first = Array.isArray(entry) ? entry[0] : void 0;
2216
+ const changes = first?.changes;
2217
+ const value = Array.isArray(changes) ? changes[0]?.value : void 0;
2218
+ const messages = value?.messages;
2219
+ const msg = Array.isArray(messages) ? messages[0] : void 0;
2220
+ if (typeof msg !== "object" || msg === null) return null;
2221
+ const m = msg;
2222
+ if (typeof m.from !== "string") return null;
2223
+ if (m.type === "text" && typeof m.text?.body === "string" && m.text.body.trim() !== "") {
2224
+ return { from: m.from, text: m.text.body.trim() };
2225
+ }
2226
+ return null;
2227
+ }
2228
+ /** 发送文本(Graph API;4096 字符上限)。 */
2229
+ async sendText(to, content) {
2230
+ const result = await postJson(
2231
+ `https://graph.facebook.com/v20.0/${encodeURIComponent(this.phoneId)}/messages`,
2232
+ {
2233
+ messaging_product: "whatsapp",
2234
+ recipient_type: "individual",
2235
+ to,
2236
+ type: "text",
2237
+ text: { body: content.slice(0, 4096) }
2238
+ },
2239
+ { authorization: `Bearer ${this.token}` }
2240
+ );
2241
+ return result !== null;
2242
+ }
2243
+ };
2244
+ async function getJson(url) {
2245
+ const controller = new AbortController();
2246
+ const timer = setTimeout(() => controller.abort(), 12e3);
2247
+ try {
2248
+ const response = await fetch(url, { signal: controller.signal });
2249
+ try {
2250
+ return await response.json();
2251
+ } catch {
2252
+ return null;
2253
+ }
2254
+ } catch (error) {
2255
+ console.warn("[dsh-message-gateway] getJson failed", url.split("?")[0], String(error));
2256
+ return null;
2257
+ } finally {
2258
+ clearTimeout(timer);
2259
+ }
2260
+ }
2261
+ async function postJson(url, body, headers = {}) {
2262
+ const controller = new AbortController();
2263
+ const timer = setTimeout(() => controller.abort(), 12e3);
2264
+ try {
2265
+ const response = await fetch(url, {
2266
+ method: "POST",
2267
+ headers: { "content-type": "application/json", ...headers },
2268
+ body: JSON.stringify(body),
2269
+ signal: controller.signal
2270
+ });
2271
+ try {
2272
+ return await response.json();
2273
+ } catch {
2274
+ return { status: response.status };
2275
+ }
2276
+ } catch (error) {
2277
+ console.warn("[dsh-message-gateway] postJson failed", url.split("?")[0], String(error));
2278
+ return null;
2279
+ } finally {
2280
+ clearTimeout(timer);
2281
+ }
2282
+ }
2283
+ function callbackIdentity(key, send) {
2284
+ const sink = {
2285
+ stream: (_frame, _sid, _content, finish) => {
2286
+ if (!finish) return;
2287
+ void send(_content);
2288
+ }
2289
+ };
2290
+ return { key, frame: {}, sink, chatType: "single" };
2291
+ }
2292
+
2293
+ // src/host/routes.ts
2294
+ var BODY_CAP_BYTES = 1 << 20;
2295
+ var CALLBACK_PATHS = {
2296
+ wecom: "/gateway/wecom/callback",
2297
+ "wechat-mp": "/gateway/wechat-mp/callback",
2298
+ whatsapp: "/gateway/whatsapp/webhook"
2299
+ };
2300
+ async function readJsonBody(req) {
2301
+ const chunks = [];
2302
+ let total = 0;
2303
+ for await (const chunk of req) {
2304
+ const part = chunk;
2305
+ total += part.length;
2306
+ if (total > BODY_CAP_BYTES) {
2307
+ req.destroy();
2308
+ return { raw: "", json: null };
2309
+ }
2310
+ chunks.push(part);
2311
+ }
2312
+ const raw = Buffer.concat(chunks).toString("utf8");
2313
+ let json2 = null;
2314
+ if (raw !== "") {
2315
+ try {
2316
+ json2 = JSON.parse(raw);
2317
+ } catch {
2318
+ json2 = null;
2319
+ }
2320
+ }
2321
+ return { raw, json: json2 };
2322
+ }
2323
+ function validSignature(secret, raw, header) {
2324
+ if (header === void 0 || header === "") return false;
2325
+ const expected = createHmac("sha256", secret).update(raw, "utf8").digest("hex");
2326
+ const a = Buffer.from(header.toLowerCase(), "utf8");
2327
+ const b = Buffer.from(expected, "utf8");
2328
+ return a.length === b.length && timingSafeEqual(a, b);
2329
+ }
2330
+ function json(res, envelope, status = 200) {
2331
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
2332
+ res.end(JSON.stringify(envelope));
2333
+ }
2334
+ async function buildView(manager) {
2335
+ const store = await loadStore();
2336
+ const status = {};
2337
+ for (const def of PLATFORMS) {
2338
+ const stored = store.statuses[def.id];
2339
+ const configured = store.platforms[def.id] !== void 0;
2340
+ let state = stored?.state ?? (def.id === "wechat" || def.id === "webhooks" ? "manual" : "none");
2341
+ let detail = stored?.detail ?? "";
2342
+ let testedAt = stored?.testedAt ?? null;
2343
+ if (def.id === "wecom-aibot" || def.id === "telegram" || def.id === "discord" || def.id === "qq" || def.id === "email") {
2344
+ const merged = manager.mergeStatus(stored, def.id);
2345
+ state = merged.state;
2346
+ detail = merged.detail;
2347
+ testedAt = merged.testedAt;
2348
+ }
2349
+ if (def.id === "wecom" || def.id === "wechat-mp" || def.id === "whatsapp") {
2350
+ if (configured) {
2351
+ state = stored?.state === "error" ? "error" : "connected";
2352
+ detail = stored?.state !== "none" && stored?.detail !== "" ? stored?.detail ?? "" : CALLBACK_PATHS[def.id] ?? "";
2353
+ testedAt = stored?.testedAt ?? testedAt;
2354
+ } else {
2355
+ state = "none";
2356
+ }
2357
+ }
2358
+ status[def.id] = { id: def.id, configured, state, detail, testedAt };
2359
+ }
2360
+ return { platforms: PLATFORMS, status };
2361
+ }
2362
+ async function handleCallbackRoute(req, res, path, query, manager) {
2363
+ const store = await loadStore();
2364
+ try {
2365
+ if (path === "/gateway/wecom/callback") {
2366
+ const cred = store.platforms.wecom;
2367
+ if (cred === void 0 || cred.token === "" || cred.encodingAESKey === "") {
2368
+ json(res, { ok: false, error: { code: "internal", message: "wecom callback not configured" } }, 400);
2369
+ return;
2370
+ }
2371
+ const bridge = new WecomAppBridge(cred.corpId ?? "", cred.agentId ?? "", cred.secret ?? "", cred.token, cred.encodingAESKey);
2372
+ if (req.method === "GET") {
2373
+ const msgSignature2 = query.get("msg_signature") ?? "";
2374
+ const timestamp2 = query.get("timestamp") ?? "";
2375
+ const nonce2 = query.get("nonce") ?? "";
2376
+ const echostr = query.get("echostr") ?? "";
2377
+ if (!bridge.verifySignature(msgSignature2, timestamp2, nonce2, echostr)) {
2378
+ json(res, { ok: false, error: { code: "internal", message: "signature mismatch" } }, 403);
2379
+ return;
2380
+ }
2381
+ try {
2382
+ const decrypted = bridge.decrypt(echostr);
2383
+ res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
2384
+ res.end(decrypted.message);
2385
+ } catch {
2386
+ json(res, { ok: false, error: { code: "internal", message: "decrypt failed" } }, 403);
2387
+ }
2388
+ return;
2389
+ }
2390
+ const { raw } = await readJsonBody(req);
2391
+ const msgSignature = query.get("msg_signature") ?? "";
2392
+ const timestamp = query.get("timestamp") ?? "";
2393
+ const nonce = query.get("nonce") ?? "";
2394
+ if (!bridge.verifySignature(msgSignature, timestamp, nonce, xmlEncrypt(raw))) {
2395
+ json(res, { ok: false, error: { code: "internal", message: "signature mismatch" } }, 403);
2396
+ return;
2397
+ }
2398
+ try {
2399
+ const decrypted = bridge.decrypt(xmlEncrypt(raw));
2400
+ const { from, text } = bridge.parseMessage(decrypted.message);
2401
+ if (from !== "" && text.trim() !== "") {
2402
+ const identity = callbackIdentity(`wecom-app:user:${from}`, (content) => bridge.sendText(from, content));
2403
+ void manager.handleExternalMessage(identity, text);
2404
+ }
2405
+ } catch (error) {
2406
+ console.error("[dsh-message-gateway] wecom-app callback decrypt failed", error);
2407
+ }
2408
+ json(res, { ok: true, value: null });
2409
+ return;
2410
+ }
2411
+ if (path === "/gateway/wechat-mp/callback") {
2412
+ const cred = store.platforms["wechat-mp"];
2413
+ if (cred === void 0 || cred.token === "") {
2414
+ json(res, { ok: false, error: { code: "internal", message: "wechat-mp callback not configured" } }, 400);
2415
+ return;
2416
+ }
2417
+ const bridge = new WechatMpBridge(cred.appId ?? "", cred.secret ?? "", cred.token);
2418
+ if (req.method === "GET") {
2419
+ const signature2 = query.get("signature") ?? "";
2420
+ const timestamp2 = query.get("timestamp") ?? "";
2421
+ const nonce2 = query.get("nonce") ?? "";
2422
+ const echostr = query.get("echostr") ?? "";
2423
+ if (!bridge.verifySignature(signature2, timestamp2, nonce2)) {
2424
+ json(res, { ok: false, error: { code: "internal", message: "signature mismatch" } }, 403);
2425
+ return;
2426
+ }
2427
+ res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
2428
+ res.end(echostr);
2429
+ return;
2430
+ }
2431
+ const { raw } = await readJsonBody(req);
2432
+ const signature = query.get("signature") ?? "";
2433
+ const timestamp = query.get("timestamp") ?? "";
2434
+ const nonce = query.get("nonce") ?? "";
2435
+ if (!bridge.verifySignature(signature, timestamp, nonce)) {
2436
+ json(res, { ok: false, error: { code: "internal", message: "signature mismatch" } }, 403);
2437
+ return;
2438
+ }
2439
+ const parsed = bridge.parseMessage(raw);
2440
+ if (parsed.msgType === "text" && parsed.from !== "" && parsed.text.trim() !== "") {
2441
+ const identity = callbackIdentity(`wechat-mp:user:${parsed.from}`, (content) => bridge.sendText(parsed.from, content));
2442
+ void manager.handleExternalMessage(identity, parsed.text);
2443
+ }
2444
+ json(res, { ok: true, value: null });
2445
+ return;
2446
+ }
2447
+ if (path === "/gateway/whatsapp/webhook") {
2448
+ const cred = store.platforms.whatsapp;
2449
+ if (cred === void 0 || cred.token === "" || cred.phoneId === "") {
2450
+ json(res, { ok: false, error: { code: "internal", message: "whatsapp not configured" } }, 400);
2451
+ return;
2452
+ }
2453
+ const bridge = new WhatsappBridge(cred.token, cred.phoneId);
2454
+ if (req.method === "GET") {
2455
+ const challenge = bridge.verifyChallenge({
2456
+ mode: query.get("hub.mode") ?? void 0,
2457
+ verify_token: query.get("hub.verify_token") ?? void 0,
2458
+ challenge: query.get("hub.challenge") ?? void 0
2459
+ });
2460
+ if (challenge === null) {
2461
+ json(res, { ok: false, error: { code: "internal", message: "verify token mismatch" } }, 403);
2462
+ return;
2463
+ }
2464
+ res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
2465
+ res.end(challenge);
2466
+ return;
2467
+ }
2468
+ const { json: payload } = await readJsonBody(req);
2469
+ const parsed = bridge.parseWebhook(payload);
2470
+ if (parsed !== null) {
2471
+ const identity = callbackIdentity(`whatsapp:${parsed.from}`, (content) => bridge.sendText(parsed.from, content));
2472
+ void manager.handleExternalMessage(identity, parsed.text);
2473
+ }
2474
+ json(res, { ok: true, value: null });
2475
+ return;
2476
+ }
2477
+ json(res, { ok: false, error: { code: "internal", message: "unknown callback route" } }, 404);
2478
+ } catch (error) {
2479
+ const message = error instanceof Error ? error.message : String(error);
2480
+ json(res, { ok: false, error: { code: "internal", message } });
2481
+ }
2482
+ }
2483
+ function extractCredentials(defId, payload) {
2484
+ const def = platformDef(defId);
2485
+ if (def === void 0) throw new Error("unknown platform");
2486
+ const out = {};
2487
+ if (typeof payload === "object" && payload !== null) {
2488
+ const record = payload;
2489
+ for (const field of def.fields) {
2490
+ const value = record[field.key];
2491
+ if (typeof value === "string") out[field.key] = value;
2492
+ }
2493
+ }
2494
+ return out;
2495
+ }
2496
+ function registerGatewayRoutes(ctx, manager) {
2497
+ return ctx.webServer.register({
2498
+ kind: "prefix",
2499
+ path: "/gateway",
2500
+ handler: async (req, res) => {
2501
+ const url = new URL(req.url ?? "/", "http://dsh");
2502
+ const path = url.pathname;
2503
+ if (path === "/gateway/wecom/callback" || path === "/gateway/wechat-mp/callback" || path === "/gateway/whatsapp/webhook") {
2504
+ await handleCallbackRoute(req, res, path, url.searchParams, manager);
2505
+ return;
2506
+ }
2507
+ if (req.method !== "POST") {
2508
+ json(res, { ok: false, error: { code: "internal", message: "method not allowed" } }, 405);
2509
+ return;
2510
+ }
2511
+ const { raw, json: payload } = await readJsonBody(req);
2512
+ const fail = (error) => {
2513
+ const message = error instanceof Error ? error.message : String(error);
2514
+ json(res, { ok: false, error: { code: "internal", message } });
2515
+ };
2516
+ try {
2517
+ if (path === "/gateway/webhook/in") {
2518
+ const store = await loadStore();
2519
+ const secret = store.platforms.webhooks?.secret ?? "";
2520
+ if (secret !== "") {
2521
+ const signature = req.headers["x-gateway-signature"];
2522
+ if (typeof signature !== "string" || !validSignature(secret, raw, signature)) {
2523
+ json(res, { ok: false, error: { code: "internal", message: "invalid signature" } }, 401);
2524
+ return;
2525
+ }
2526
+ }
2527
+ const body = payload;
2528
+ const text = [body?.text, body?.content, body?.message].map((value) => typeof value === "string" ? value : "").find((value) => value.trim() !== "") ?? "";
2529
+ if (text === "") {
2530
+ json(res, { ok: false, error: { code: "internal", message: "missing text" } }, 400);
2531
+ return;
2532
+ }
2533
+ const result = await manager.sendAndWait(text);
2534
+ if (!result.ok) {
2535
+ json(res, { ok: false, error: { code: "internal", message: result.reply } }, 409);
2536
+ return;
2537
+ }
2538
+ json(res, { ok: true, value: { reply: result.reply } });
2539
+ return;
2540
+ }
2541
+ if (path === "/gateway/wechat-status") {
2542
+ const store = await loadStore();
2543
+ const cred = store.platforms.wechat ?? {};
2544
+ const base = (cred.gatewayUrl ?? "").trim().replace(/\/$/, "");
2545
+ if (base === "") {
2546
+ json(res, { ok: true, value: { configured: false, loggedIn: false, name: "", qrcode: null, qrcodeUrl: null, error: "" } });
2547
+ return;
2548
+ }
2549
+ const controller = new AbortController();
2550
+ const timer = setTimeout(() => controller.abort(), 8e3);
2551
+ try {
2552
+ const headers = { accept: "application/json" };
2553
+ if (typeof cred.token === "string" && cred.token !== "") headers.authorization = `Bearer ${cred.token}`;
2554
+ const response = await fetch(`${base}/status`, { headers, signal: controller.signal });
2555
+ if (!response.ok) {
2556
+ json(res, { ok: true, value: { configured: true, loggedIn: false, name: "", qrcode: null, qrcodeUrl: null, error: `HTTP ${response.status}` } });
2557
+ return;
2558
+ }
2559
+ const r = await response.json();
2560
+ json(res, {
2561
+ ok: true,
2562
+ value: {
2563
+ configured: true,
2564
+ loggedIn: r.loggedIn === true,
2565
+ name: r.name ?? "",
2566
+ qrcode: typeof r.qrcode === "string" && r.qrcode !== "" ? r.qrcode : null,
2567
+ qrcodeUrl: typeof r.qrcodeUrl === "string" && r.qrcodeUrl !== "" ? r.qrcodeUrl : null,
2568
+ error: ""
2569
+ }
2570
+ });
2571
+ } catch (error) {
2572
+ json(res, {
2573
+ ok: true,
2574
+ value: { configured: true, loggedIn: false, name: "", qrcode: null, qrcodeUrl: null, error: error instanceof Error ? error.message : String(error) }
2575
+ });
2576
+ } finally {
2577
+ clearTimeout(timer);
2578
+ }
2579
+ return;
2580
+ }
2581
+ if (path === "/gateway/send") {
2582
+ const body = payload;
2583
+ const chatid = typeof body?.chatid === "string" ? body.chatid.trim() : "";
2584
+ const content = typeof body?.content === "string" ? body.content.trim() : "";
2585
+ if (chatid === "" || content === "") {
2586
+ json(res, { ok: false, error: { code: "internal", message: "missing chatid/content" } }, 400);
2587
+ return;
2588
+ }
2589
+ const sent = await manager.sendToChat(chatid, content);
2590
+ if (!sent) {
2591
+ json(res, { ok: false, error: { code: "internal", message: "send failed (bridge not connected?)" } }, 409);
2592
+ return;
2593
+ }
2594
+ json(res, { ok: true, value: { sent: true } });
2595
+ return;
2596
+ }
2597
+ if (path === "/gateway/list") {
2598
+ json(res, { ok: true, value: await buildView(manager) });
2599
+ return;
2600
+ }
2601
+ if (path === "/gateway/save" || path === "/gateway/delete" || path === "/gateway/test") {
2602
+ const platform = payload?.platform;
2603
+ if (typeof platform !== "string") {
2604
+ json(res, { ok: false, error: { code: "internal", message: "missing platform" } });
2605
+ return;
2606
+ }
2607
+ const store = await loadStore();
2608
+ if (path === "/gateway/delete") {
2609
+ delete store.platforms[platform];
2610
+ delete store.statuses[platform];
2611
+ await saveStore(store);
2612
+ if (platform === "wecom-aibot") manager.stopWecom();
2613
+ if (platform === "telegram") manager.stopTelegram();
2614
+ if (platform === "discord") manager.stopDiscord();
2615
+ if (platform === "qq") manager.stopQQ();
2616
+ if (platform === "email") manager.stopEmail();
2617
+ json(res, { ok: true, value: await buildView(manager) });
2618
+ return;
2619
+ }
2620
+ if (path === "/gateway/save") {
2621
+ const credentials2 = extractCredentials(platform, payload);
2622
+ const def = platformDef(platform);
2623
+ if (def !== void 0 && def.fields.length > 0 && Object.keys(credentials2).length === 0) {
2624
+ json(res, { ok: false, error: { code: "internal", message: "empty credentials" } });
2625
+ return;
2626
+ }
2627
+ store.platforms[platform] = credentials2;
2628
+ delete store.statuses[platform];
2629
+ await saveStore(store);
2630
+ if (platform === "wecom-aibot") {
2631
+ if (credentials2.botId !== "" && credentials2.secret !== "") {
2632
+ manager.startWecom({ botId: credentials2.botId, secret: credentials2.secret });
2633
+ } else {
2634
+ manager.stopWecom();
2635
+ }
2636
+ }
2637
+ if (platform === "telegram") {
2638
+ if (credentials2.token !== void 0 && credentials2.token !== "") manager.startTelegram(credentials2);
2639
+ else manager.stopTelegram();
2640
+ }
2641
+ if (platform === "discord") {
2642
+ if (credentials2.token !== void 0 && credentials2.token !== "") manager.startDiscord(credentials2);
2643
+ else manager.stopDiscord();
2644
+ }
2645
+ if (platform === "qq") {
2646
+ if (credentials2.appId !== void 0 && credentials2.appId !== "" && credentials2.secret !== void 0 && credentials2.secret !== "") {
2647
+ manager.startQQ(credentials2);
2648
+ } else {
2649
+ manager.stopQQ();
2650
+ }
2651
+ }
2652
+ if (platform === "email") {
2653
+ if (credentials2.imapHost !== void 0 && credentials2.imapHost !== "" && credentials2.imapUser !== void 0 && credentials2.imapUser !== "") {
2654
+ manager.startEmail(credentials2);
2655
+ } else {
2656
+ manager.stopEmail();
2657
+ }
2658
+ }
2659
+ json(res, { ok: true, value: await buildView(manager) });
2660
+ return;
2661
+ }
2662
+ const submitted = extractCredentials(platform, payload);
2663
+ const hasSubmitted = Object.keys(submitted).length > 0;
2664
+ const credentials = hasSubmitted ? submitted : store.platforms[platform] ?? {};
2665
+ const result = await testPlatform(platform, credentials);
2666
+ const stored = {
2667
+ state: result.ok ? "connected" : "error",
2668
+ detail: result.detail,
2669
+ testedAt: Date.now()
2670
+ };
2671
+ store.statuses[platform] = stored;
2672
+ await saveStore(store);
2673
+ json(res, { ok: true, value: { ok: result.ok, detail: result.detail } });
2674
+ return;
2675
+ }
2676
+ json(res, { ok: false, error: { code: "internal", message: "unknown route" } }, 404);
2677
+ } catch (error) {
2678
+ fail(error);
2679
+ }
2680
+ }
2681
+ });
2682
+ }
2683
+
2684
+ // src/core/config.ts
2685
+ import Schema from "@deepseek-ai/schemastery";
2686
+ var Config = Schema.object({
2687
+ botLocale: Schema.union(["zh", "en"]).default("zh").description("\u673A\u5668\u4EBA\u56DE\u590D\u8BED\u8A00\uFF08zh \u4E2D\u6587 / en English\uFF09"),
2688
+ maxChatAgents: Schema.natural().min(1).max(200).default(40).description("\u6BCF\u4E2A\u673A\u5668\u4EBA\u6700\u591A\u4FDD\u7559\u7684\u804A\u5929\u4F1A\u8BDD\u6570\uFF0C\u8D85\u51FA\u81EA\u52A8\u6DD8\u6C70\u6700\u65E7\u4F1A\u8BDD"),
2689
+ botModel: Schema.object({
2690
+ provider: Schema.string().required().description("\u6A21\u578B\u4F9B\u5E94\u5546\uFF08\u5982 pipio / opencode-go\uFF09"),
2691
+ model: Schema.string().required().description("\u6A21\u578B id\uFF08\u5982 deepseek-v4-flash-0731\uFF09")
2692
+ }).default(void 0).description("\u53EF\u9009\uFF1A\u673A\u5668\u4EBA\u4E13\u7528\u6A21\u578B\uFF0C\u4F18\u5148\u4E8E\u90E8\u7F72\u9ED8\u8BA4\u6A21\u578B\uFF08\u4E0D\u586B\u5219\u4E0E Web \u5BF9\u8BDD\u4E00\u81F4\uFF09"),
2693
+ autoStartWecom: Schema.boolean().default(true).description("\u542F\u52A8\u65F6\u81EA\u52A8\u7528\u5DF2\u4FDD\u5B58\u7684\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA\u51ED\u636E\u5EFA\u7ACB\u5E38\u9A7B\u8FDE\u63A5"),
2694
+ autoStartTelegram: Schema.boolean().default(true).description("\u542F\u52A8\u65F6\u81EA\u52A8\u7528\u5DF2\u4FDD\u5B58\u7684 Telegram \u51ED\u636E\u5EFA\u7ACB\u5E38\u9A7B\u8FDE\u63A5"),
2695
+ autoStartDiscord: Schema.boolean().default(true).description("\u542F\u52A8\u65F6\u81EA\u52A8\u7528\u5DF2\u4FDD\u5B58\u7684 Discord \u51ED\u636E\u5EFA\u7ACB\u5E38\u9A7B\u8FDE\u63A5"),
2696
+ autoStartQQ: Schema.boolean().default(true).description("\u542F\u52A8\u65F6\u81EA\u52A8\u7528\u5DF2\u4FDD\u5B58\u7684 QQ \u51ED\u636E\u5EFA\u7ACB\u5E38\u9A7B\u8FDE\u63A5"),
2697
+ autoStartEmail: Schema.boolean().default(true).description("\u542F\u52A8\u65F6\u81EA\u52A8\u7528\u5DF2\u4FDD\u5B58\u7684 Email \u51ED\u636E\u5EFA\u7ACB\u5E38\u9A7B\u8FDE\u63A5\uFF08IMAP \u8F6E\u8BE2\uFF09"),
2698
+ groupReply: Schema.boolean().default(true).description("\u662F\u5426\u56DE\u590D\u7FA4\u804A\u6D88\u606F\uFF08false \u65F6\u53EA\u5904\u7406\u5355\u804A\uFF09")
2699
+ });
2700
+
2701
+ // src/index.ts
2702
+ var inject = ["webServer", "sessions", "agents", "agentDefaultModel"];
2703
+ function apply(ctx, config = Config({})) {
2704
+ const manager = new BridgeManager(ctx, config);
2705
+ ctx.effect(() => {
2706
+ void loadStore().then((store) => {
2707
+ const wecom = store.platforms["wecom-aibot"];
2708
+ if (config.autoStartWecom && wecom !== void 0 && wecom.botId !== "" && wecom.secret !== "") {
2709
+ manager.startWecom({ botId: wecom.botId, secret: wecom.secret });
2710
+ console.log("[dsh-message-gateway] wecom-aibot bridge auto-started");
2711
+ }
2712
+ const telegram = store.platforms.telegram;
2713
+ if (config.autoStartTelegram && telegram !== void 0 && telegram.token !== "") {
2714
+ manager.startTelegram(telegram);
2715
+ console.log("[dsh-message-gateway] telegram bridge auto-started");
2716
+ }
2717
+ const discord = store.platforms.discord;
2718
+ if (config.autoStartDiscord && discord !== void 0 && discord.token !== "") {
2719
+ manager.startDiscord(discord);
2720
+ console.log("[dsh-message-gateway] discord bridge auto-started");
2721
+ }
2722
+ const qq = store.platforms.qq;
2723
+ if (config.autoStartQQ && qq !== void 0 && qq.appId !== "" && qq.secret !== "") {
2724
+ manager.startQQ(qq);
2725
+ console.log("[dsh-message-gateway] qq bridge auto-started");
2726
+ }
2727
+ const email = store.platforms.email;
2728
+ if (config.autoStartEmail && email !== void 0 && email.imapHost !== "" && email.imapUser !== "") {
2729
+ manager.startEmail(email);
2730
+ console.log("[dsh-message-gateway] email bridge auto-started");
2731
+ }
2732
+ });
2733
+ const disposeRoutes = registerGatewayRoutes(ctx, manager);
2734
+ return () => {
2735
+ disposeRoutes();
2736
+ void manager.dispose();
2737
+ };
2738
+ }, "dsh-message-gateway: routes + bridges");
2739
+ }
2740
+ var index_default = { apply, inject, Config };
2741
+ export {
2742
+ BridgeManager,
2743
+ CALLBACK_PATHS,
2744
+ Config,
2745
+ DiscordBridge,
2746
+ EmailBridge,
2747
+ ImapClient,
2748
+ PLATFORMS,
2749
+ QQBridge,
2750
+ SmtpClient,
2751
+ TelegramBridge,
2752
+ WechatMpBridge,
2753
+ WecomAppBridge,
2754
+ WecomBridge,
2755
+ WhatsappBridge,
2756
+ apply,
2757
+ cleanBody,
2758
+ index_default as default,
2759
+ headerField,
2760
+ inject,
2761
+ parseAddress,
2762
+ platformDef,
2763
+ sha1Sorted,
2764
+ testPlatform,
2765
+ xmlEncrypt,
2766
+ xmlField
2767
+ };
2768
+ //# sourceMappingURL=index.js.map