dsh-message-gateway 0.1.32 → 0.1.35

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 CHANGED
@@ -8,6 +8,435 @@ var __export = (target, all) => {
8
8
  __defProp(target, name, { get: all[name], enumerable: true });
9
9
  };
10
10
 
11
+ // src/host/incoming.ts
12
+ async function downloadBytes(url, opts = {}) {
13
+ const { timeoutMs = 6e4, maxBytes = 100 * 1024 * 1024, headers } = opts;
14
+ if (!/^https?:\/\//i.test(url)) throw new Error("\u975E\u6CD5\u4E0B\u8F7D\u5730\u5740");
15
+ const controller = new AbortController();
16
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
17
+ try {
18
+ const response = await fetch(url, { headers, signal: controller.signal });
19
+ if (!response.ok) throw new Error(`\u4E0B\u8F7D\u5931\u8D25 HTTP ${response.status}`);
20
+ const contentLength = Number(response.headers.get("content-length") ?? "0");
21
+ if (contentLength > maxBytes) throw new Error("\u9644\u4EF6\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650");
22
+ const buf = new Uint8Array(await response.arrayBuffer());
23
+ if (buf.byteLength > maxBytes) throw new Error("\u9644\u4EF6\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650");
24
+ return buf;
25
+ } finally {
26
+ clearTimeout(timer);
27
+ }
28
+ }
29
+ async function collectStream(stream) {
30
+ const chunks = [];
31
+ let total = 0;
32
+ const iterable = stream;
33
+ for await (const chunk of iterable) {
34
+ chunks.push(chunk);
35
+ total += chunk.byteLength;
36
+ }
37
+ const out = new Uint8Array(total);
38
+ let offset = 0;
39
+ for (const chunk of chunks) {
40
+ out.set(chunk, offset);
41
+ offset += chunk.byteLength;
42
+ }
43
+ return out;
44
+ }
45
+ var init_incoming = __esm({
46
+ "src/host/incoming.ts"() {
47
+ "use strict";
48
+ }
49
+ });
50
+
51
+ // src/host/wechat-ilink-bridge.ts
52
+ var wechat_ilink_bridge_exports = {};
53
+ __export(wechat_ilink_bridge_exports, {
54
+ WechatIlinkBridge: () => WechatIlinkBridge
55
+ });
56
+ import crypto from "node:crypto";
57
+ function parseIlinkAesKey(aesKeyBase64) {
58
+ const decoded = Buffer.from(aesKeyBase64, "base64");
59
+ if (decoded.length === 16) return decoded;
60
+ if (decoded.length === 32 && /^[0-9a-fA-F]{32}$/.test(decoded.toString("ascii"))) {
61
+ return Buffer.from(decoded.toString("ascii"), "hex");
62
+ }
63
+ throw new Error(`aes_key \u65E0\u6CD5\u8BC6\u522B\uFF08\u89E3\u7801\u540E ${decoded.length} \u5B57\u8282\uFF09`);
64
+ }
65
+ function ilinkMediaUrl(media) {
66
+ if (typeof media.full_url === "string" && media.full_url !== "") return media.full_url;
67
+ const param = typeof media.encrypt_query_param === "string" ? media.encrypt_query_param : "";
68
+ return `${ILINK_CDN_BASE}/download?encrypted_query_param=${encodeURIComponent(param)}`;
69
+ }
70
+ async function downloadIlinkMedia(media) {
71
+ const encrypted = await downloadBytes(ilinkMediaUrl(media), { maxBytes: ILINK_MEDIA_MAX_BYTES });
72
+ const aesKey = typeof media.aes_key === "string" ? media.aes_key : "";
73
+ if (aesKey === "") return encrypted;
74
+ const key = parseIlinkAesKey(aesKey);
75
+ const decipher = crypto.createDecipheriv("aes-128-ecb", key, null);
76
+ return new Uint8Array(Buffer.concat([decipher.update(Buffer.from(encrypted)), decipher.final()]));
77
+ }
78
+ var ILINK_BASE_URL, ILINK_APP_ID, ILINK_CLIENT_VERSION, ILINK_CDN_BASE, ILINK_MEDIA_MAX_BYTES, ITEM_TEXT, ITEM_IMAGE, ITEM_VOICE, ITEM_FILE, ITEM_VIDEO, WechatIlinkBridge;
79
+ var init_wechat_ilink_bridge = __esm({
80
+ "src/host/wechat-ilink-bridge.ts"() {
81
+ "use strict";
82
+ init_incoming();
83
+ ILINK_BASE_URL = "https://ilinkai.weixin.qq.com";
84
+ ILINK_APP_ID = "bot";
85
+ ILINK_CLIENT_VERSION = (2 & 255) << 16 | (4 & 255) << 8 | 8 & 255;
86
+ ILINK_CDN_BASE = "https://novac2c.cdn.weixin.qq.com/c2c";
87
+ ILINK_MEDIA_MAX_BYTES = 100 * 1024 * 1024;
88
+ ITEM_TEXT = 1;
89
+ ITEM_IMAGE = 2;
90
+ ITEM_VOICE = 3;
91
+ ITEM_FILE = 4;
92
+ ITEM_VIDEO = 5;
93
+ WechatIlinkBridge = class _WechatIlinkBridge {
94
+ stopped = false;
95
+ pollController = null;
96
+ syncBuf = "";
97
+ cred;
98
+ callbacks;
99
+ status = { state: "idle", detail: "", connectedAt: null };
100
+ constructor(cred, callbacks) {
101
+ this.cred = cred;
102
+ this.callbacks = callbacks;
103
+ }
104
+ setStatus(state, detail = "") {
105
+ this.status = {
106
+ state,
107
+ detail,
108
+ connectedAt: state === "connected" ? this.status.connectedAt ?? Date.now() : null
109
+ };
110
+ this.callbacks.onStatus(this.status);
111
+ }
112
+ static randomWechatUin() {
113
+ const uint32 = crypto.randomBytes(4).readUInt32BE(0);
114
+ return Buffer.from(String(uint32), "utf-8").toString("base64");
115
+ }
116
+ static buildHeaders(token) {
117
+ const headers = {
118
+ "Content-Type": "application/json",
119
+ "iLink-App-Id": ILINK_APP_ID,
120
+ "iLink-App-ClientVersion": String(ILINK_CLIENT_VERSION),
121
+ "X-WECHAT-UIN": _WechatIlinkBridge.randomWechatUin()
122
+ };
123
+ if (token?.trim()) {
124
+ headers["Authorization"] = `Bearer ${token.trim()}`;
125
+ headers["AuthorizationType"] = "ilink_bot_token";
126
+ }
127
+ return headers;
128
+ }
129
+ /**
130
+ * 生成微信扫码登录二维码。
131
+ * 返回 qrcode key 与完整二维码展示图片/扫码 URL。
132
+ */
133
+ static async getLoginQr() {
134
+ const url = `${ILINK_BASE_URL}/ilink/bot/get_bot_qrcode?bot_type=3`;
135
+ const resp = await fetch(url, {
136
+ method: "POST",
137
+ headers: _WechatIlinkBridge.buildHeaders(),
138
+ body: JSON.stringify({ local_token_list: [] }),
139
+ signal: AbortSignal.timeout(15e3)
140
+ });
141
+ if (!resp.ok) {
142
+ throw new Error(`get_bot_qrcode failed: HTTP ${resp.status}`);
143
+ }
144
+ const data = await resp.json();
145
+ const qrcode = data.qrcode;
146
+ const rawTarget = data.qrcode_img_content || `https://ilinkai.weixin.qq.com/ilink/bot/get_qrcode_img?qrcode=${encodeURIComponent(qrcode)}`;
147
+ let qrcodeUrl = rawTarget;
148
+ try {
149
+ const QRCode = await import("qrcode");
150
+ qrcodeUrl = await QRCode.toDataURL(rawTarget, { width: 220, margin: 1 });
151
+ } catch (e) {
152
+ console.warn("[dsh-message-gateway] QRCode.toDataURL error", e);
153
+ }
154
+ return { qrcode, qrcodeUrl };
155
+ }
156
+ /**
157
+ * 轮询扫码状态。
158
+ */
159
+ static async pollQrStatus(qrcode) {
160
+ const url = `${ILINK_BASE_URL}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(qrcode)}`;
161
+ const resp = await fetch(url, {
162
+ method: "GET",
163
+ headers: _WechatIlinkBridge.buildHeaders(),
164
+ signal: AbortSignal.timeout(35e3)
165
+ });
166
+ if (!resp.ok) {
167
+ return { status: "wait" };
168
+ }
169
+ const data = await resp.json();
170
+ return {
171
+ status: data.status,
172
+ botToken: data.bot_token,
173
+ baseUrl: data.baseurl || ILINK_BASE_URL,
174
+ botId: data.ilink_bot_id,
175
+ userId: data.ilink_user_id
176
+ };
177
+ }
178
+ /**
179
+ * 启动长轮询消息监听。
180
+ */
181
+ start() {
182
+ if (this.status.state === "connected") return;
183
+ this.stopped = false;
184
+ const label = this.cred.nickname || this.cred.userId ? `@${this.cred.nickname || this.cred.userId}` : "\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA";
185
+ this.setStatus("connected", label);
186
+ console.log("[dsh-message-gateway] wechat ilink bridge started for", label);
187
+ void this.pollLoop();
188
+ }
189
+ async pollLoop() {
190
+ const baseUrl = this.cred.baseUrl || ILINK_BASE_URL;
191
+ while (!this.stopped) {
192
+ try {
193
+ this.pollController = new AbortController();
194
+ const timeoutId = setTimeout(() => this.pollController?.abort(), 35e3);
195
+ const resp = await fetch(`${baseUrl}/ilink/bot/getupdates`, {
196
+ method: "POST",
197
+ headers: _WechatIlinkBridge.buildHeaders(this.cred.botToken),
198
+ body: JSON.stringify({
199
+ get_updates_buf: this.syncBuf,
200
+ base_info: { channel_version: "2.4.8", bot_agent: "DSH-Message-Gateway" }
201
+ }),
202
+ signal: this.pollController.signal
203
+ });
204
+ clearTimeout(timeoutId);
205
+ if (!resp.ok) {
206
+ if (resp.status === 401 || resp.status === 403) {
207
+ this.setStatus("error", "Token \u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u626B\u7801");
208
+ break;
209
+ }
210
+ await new Promise((r) => setTimeout(r, 3e3));
211
+ continue;
212
+ }
213
+ const data = await resp.json();
214
+ if (data.get_updates_buf) {
215
+ this.syncBuf = data.get_updates_buf;
216
+ }
217
+ const msgs = data.msgs ?? [];
218
+ for (const msg of msgs) {
219
+ if (msg.message_type !== 1) continue;
220
+ void this.handleInboundMessage(msg);
221
+ }
222
+ } catch (err) {
223
+ if (this.stopped) break;
224
+ const isAbort = err instanceof Error && err.name === "AbortError";
225
+ if (!isAbort) {
226
+ console.warn("[dsh-message-gateway] wechat getupdates error, retrying in 2s:", err);
227
+ await new Promise((r) => setTimeout(r, 2e3));
228
+ }
229
+ }
230
+ }
231
+ }
232
+ /**
233
+ * 处理单条从微信拉取到的消息。
234
+ */
235
+ async handleInboundMessage(msg) {
236
+ const fromUser = String(msg.from_user_id ?? "");
237
+ if (!fromUser) return;
238
+ let text = "";
239
+ const attachments = [];
240
+ const notes = [];
241
+ const items = Array.isArray(msg.item_list) ? msg.item_list : [];
242
+ for (const item of items) {
243
+ if (item.type === ITEM_TEXT && item.text_item?.text) {
244
+ text += (text ? "\n" : "") + String(item.text_item.text).trim();
245
+ continue;
246
+ }
247
+ if (item.type === ITEM_IMAGE) {
248
+ const img = item.image_item;
249
+ if (img?.media === void 0) continue;
250
+ try {
251
+ const aesKey = typeof img.aeskey === "string" && img.aeskey !== "" ? Buffer.from(img.aeskey, "hex").toString("base64") : img.media.aes_key;
252
+ const data = await downloadIlinkMedia({ ...img.media, aes_key: aesKey });
253
+ attachments.push({ kind: "image", data });
254
+ } catch (error) {
255
+ notes.push(`\uFF08\u56FE\u7247\u63A5\u6536\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
256
+ }
257
+ continue;
258
+ }
259
+ if (item.type === ITEM_VOICE) {
260
+ const voice = item.voice_item;
261
+ if (typeof voice?.text === "string" && voice.text.trim() !== "") {
262
+ text += (text ? "\n" : "") + voice.text.trim();
263
+ }
264
+ if (voice?.media !== void 0) {
265
+ try {
266
+ const data = await downloadIlinkMedia(voice.media);
267
+ attachments.push({ kind: "file", data, name: "voice.silk" });
268
+ } catch (error) {
269
+ notes.push(`\uFF08\u8BED\u97F3\u63A5\u6536\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
270
+ }
271
+ }
272
+ continue;
273
+ }
274
+ if (item.type === ITEM_FILE || item.type === ITEM_VIDEO) {
275
+ const node = item.type === ITEM_FILE ? item.file_item : item.video_item;
276
+ if (node?.media === void 0) continue;
277
+ const fallbackName = item.type === ITEM_FILE ? "file.bin" : "video.mp4";
278
+ const name = typeof node.file_name === "string" && node.file_name !== "" ? node.file_name : fallbackName;
279
+ try {
280
+ const data = await downloadIlinkMedia(node.media);
281
+ attachments.push({ kind: "file", data, name });
282
+ } catch (error) {
283
+ notes.push(`\uFF08${item.type === ITEM_FILE ? "\u6587\u4EF6" : "\u89C6\u9891"}\u63A5\u6536\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
284
+ }
285
+ continue;
286
+ }
287
+ }
288
+ if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
289
+ ${notes.join("\n")}`;
290
+ if (text === "" && attachments.length === 0) return;
291
+ const contextToken = msg.context_token ?? "";
292
+ const sessionId = msg.session_id || fromUser;
293
+ const frame = {
294
+ fromUser,
295
+ contextToken,
296
+ sessionId,
297
+ msgId: msg.message_id
298
+ };
299
+ let typingTimer = null;
300
+ let typingTicket = "";
301
+ const startTyping = async () => {
302
+ try {
303
+ typingTicket = await this.getTypingTicket(fromUser, contextToken);
304
+ if (typingTicket) {
305
+ await this.sendTypingIndicator(fromUser, typingTicket);
306
+ typingTimer = setInterval(() => {
307
+ void this.sendTypingIndicator(fromUser, typingTicket);
308
+ }, 4500);
309
+ }
310
+ } catch (err) {
311
+ console.warn("[dsh-message-gateway] wechat startTyping failed", err);
312
+ }
313
+ };
314
+ void startTyping();
315
+ const sink = {
316
+ stream: (_f, _streamId, content, finish) => {
317
+ if (finish) {
318
+ if (typingTimer) {
319
+ clearInterval(typingTimer);
320
+ typingTimer = null;
321
+ }
322
+ if (content.trim()) {
323
+ void this.sendMessage(fromUser, content, contextToken);
324
+ }
325
+ }
326
+ },
327
+ ack: false
328
+ };
329
+ const identity = {
330
+ key: `wechat:${sessionId}`,
331
+ frame,
332
+ sink,
333
+ chatType: msg.group_id ? "group" : "single"
334
+ };
335
+ this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
336
+ }
337
+ /**
338
+ * 获取微信用户的 typing_ticket(打字态凭证)。
339
+ */
340
+ async getTypingTicket(userId, contextToken) {
341
+ const baseUrl = this.cred.baseUrl || ILINK_BASE_URL;
342
+ try {
343
+ const resp = await fetch(`${baseUrl}/ilink/bot/getconfig`, {
344
+ method: "POST",
345
+ headers: _WechatIlinkBridge.buildHeaders(this.cred.botToken),
346
+ body: JSON.stringify({
347
+ ilink_user_id: userId,
348
+ context_token: contextToken || "",
349
+ base_info: { channel_version: "2.4.8", bot_agent: "DSH-Message-Gateway" }
350
+ }),
351
+ signal: AbortSignal.timeout(8e3)
352
+ });
353
+ if (!resp.ok) return "";
354
+ const data = await resp.json();
355
+ return data.typing_ticket ?? "";
356
+ } catch {
357
+ return "";
358
+ }
359
+ }
360
+ /**
361
+ * 向微信客户端发送「对方正在输入…」指示。
362
+ */
363
+ async sendTypingIndicator(toUserId, typingTicket) {
364
+ if (!typingTicket) return false;
365
+ const baseUrl = this.cred.baseUrl || ILINK_BASE_URL;
366
+ try {
367
+ const resp = await fetch(`${baseUrl}/ilink/bot/sendtyping`, {
368
+ method: "POST",
369
+ headers: _WechatIlinkBridge.buildHeaders(this.cred.botToken),
370
+ body: JSON.stringify({
371
+ ilink_user_id: toUserId,
372
+ typing_ticket: typingTicket,
373
+ base_info: { channel_version: "2.4.8", bot_agent: "DSH-Message-Gateway" }
374
+ }),
375
+ signal: AbortSignal.timeout(6e3)
376
+ });
377
+ if (!resp.ok) return false;
378
+ const data = await resp.json();
379
+ return data.ret === 0;
380
+ } catch {
381
+ return false;
382
+ }
383
+ }
384
+ /**
385
+ * 发送回复消息回微信用户。
386
+ */
387
+ async sendMessage(toUserId, content, contextToken) {
388
+ const baseUrl = this.cred.baseUrl || ILINK_BASE_URL;
389
+ const clientId = `dsh-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
390
+ try {
391
+ const resp = await fetch(`${baseUrl}/ilink/bot/sendmessage`, {
392
+ method: "POST",
393
+ headers: _WechatIlinkBridge.buildHeaders(this.cred.botToken),
394
+ body: JSON.stringify({
395
+ msg: {
396
+ from_user_id: "",
397
+ to_user_id: toUserId,
398
+ client_id: clientId,
399
+ message_type: 2,
400
+ // BOT
401
+ message_state: 2,
402
+ // FINISH
403
+ context_token: contextToken || "",
404
+ item_list: [
405
+ {
406
+ type: 1,
407
+ // TEXT
408
+ text_item: { text: content }
409
+ }
410
+ ]
411
+ },
412
+ base_info: { channel_version: "2.4.8", bot_agent: "DSH-Message-Gateway" }
413
+ }),
414
+ signal: AbortSignal.timeout(15e3)
415
+ });
416
+ if (!resp.ok) {
417
+ console.error("[dsh-message-gateway] wechat sendmessage failed:", resp.status);
418
+ return false;
419
+ }
420
+ const data = await resp.json();
421
+ return data.ret === 0;
422
+ } catch (err) {
423
+ console.error("[dsh-message-gateway] wechat sendmessage error:", err);
424
+ return false;
425
+ }
426
+ }
427
+ /**
428
+ * 停止微信长轮询连接。
429
+ */
430
+ stop() {
431
+ this.stopped = true;
432
+ this.pollController?.abort();
433
+ this.pollController = null;
434
+ this.setStatus("idle");
435
+ }
436
+ };
437
+ }
438
+ });
439
+
11
440
  // src/host/gateway-store.ts
12
441
  var gateway_store_exports = {};
13
442
  __export(gateway_store_exports, {
@@ -379,6 +808,64 @@ var WecomBridge = class {
379
808
  const content = frame.body?.text?.content ?? "";
380
809
  if (content.trim() !== "") this.callbacks.onText(content, frame);
381
810
  });
811
+ client.on("message.image", async (frame) => {
812
+ const img = frame.body?.image;
813
+ if (img?.url === void 0 || img.url === "") return;
814
+ try {
815
+ const { buffer, filename } = await client.downloadFile(img.url, img.aeskey);
816
+ if (buffer.byteLength === 0) throw new Error("\u4E0B\u8F7D\u7ED3\u679C\u4E3A\u7A7A");
817
+ this.callbacks.onText("", frame, [{ kind: "image", data: new Uint8Array(buffer), name: filename }]);
818
+ } catch (err) {
819
+ this.callbacks.onText(`\uFF08\u56FE\u7247\u63A5\u6536\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}\uFF09`, frame);
820
+ }
821
+ });
822
+ client.on("message.file", async (frame) => {
823
+ const f = frame.body?.file;
824
+ if (f?.url === void 0 || f.url === "") return;
825
+ try {
826
+ const { buffer, filename } = await client.downloadFile(f.url, f.aeskey);
827
+ if (buffer.byteLength === 0) throw new Error("\u4E0B\u8F7D\u7ED3\u679C\u4E3A\u7A7A");
828
+ this.callbacks.onText("", frame, [{ kind: "file", data: new Uint8Array(buffer), name: filename }]);
829
+ } catch (err) {
830
+ this.callbacks.onText(`\uFF08\u6587\u4EF6\u63A5\u6536\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}\uFF09`, frame);
831
+ }
832
+ });
833
+ client.on("message.video", async (frame) => {
834
+ const v = frame.body?.video;
835
+ if (v?.url === void 0 || v.url === "") return;
836
+ try {
837
+ const { buffer, filename } = await client.downloadFile(v.url, v.aeskey);
838
+ if (buffer.byteLength === 0) throw new Error("\u4E0B\u8F7D\u7ED3\u679C\u4E3A\u7A7A");
839
+ this.callbacks.onText("", frame, [{ kind: "file", data: new Uint8Array(buffer), name: filename ?? "video.mp4" }]);
840
+ } catch (err) {
841
+ this.callbacks.onText(`\uFF08\u89C6\u9891\u63A5\u6536\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}\uFF09`, frame);
842
+ }
843
+ });
844
+ client.on("message.mixed", async (frame) => {
845
+ const items = frame.body?.mixed?.msg_item ?? [];
846
+ const texts = [];
847
+ const attachments = [];
848
+ for (const item of items) {
849
+ if (item.msgtype === "text") {
850
+ const t = item.text?.content ?? "";
851
+ if (t.trim() !== "") texts.push(t.trim());
852
+ } else if (item.msgtype === "image" && item.image?.url) {
853
+ try {
854
+ const { buffer } = await client.downloadFile(item.image.url, item.image.aeskey);
855
+ if (buffer.byteLength > 0) {
856
+ attachments.push({ kind: "image", data: new Uint8Array(buffer) });
857
+ }
858
+ } catch (err) {
859
+ texts.push(`\uFF08\u56FE\u7247\u63A5\u6536\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}\uFF09`);
860
+ }
861
+ }
862
+ }
863
+ this.callbacks.onText(texts.join("\n"), frame, attachments.length > 0 ? attachments : void 0);
864
+ });
865
+ client.on("message.voice", (frame) => {
866
+ const content = frame.body?.voice?.content ?? "";
867
+ if (content.trim() !== "") this.callbacks.onText(content, frame);
868
+ });
382
869
  client.on("event.enter_chat", (frame) => {
383
870
  this.callbacks.onEnter(frame);
384
871
  });
@@ -518,11 +1005,25 @@ async function smartFetch(url, init) {
518
1005
  json: () => res.json()
519
1006
  };
520
1007
  }
1008
+ async function smartFetchBinary(url, init) {
1009
+ const urlStr = String(url);
1010
+ const isOverseas = /discord\.com|discordapp\.com|telegram\.org|api\.openai\.com/i.test(urlStr);
1011
+ if (isOverseas) {
1012
+ const dispatcher = await getProxyDispatcher();
1013
+ if (dispatcher) {
1014
+ const res2 = await undiciFetch(urlStr, { ...init, dispatcher });
1015
+ return { status: res2.status, arrayBuffer: () => res2.arrayBuffer() };
1016
+ }
1017
+ }
1018
+ const res = await fetch(url, init);
1019
+ return { status: res.status, arrayBuffer: () => res.arrayBuffer() };
1020
+ }
521
1021
 
522
1022
  // src/host/telegram-bridge.ts
523
1023
  var EDIT_INTERVAL_MS = 1200;
524
1024
  var MSG_LIMIT = 4096;
525
1025
  var POLL_TIMEOUT = 25;
1026
+ var TG_DOWNLOAD_LIMIT = 20 * 1024 * 1024;
526
1027
  var TelegramBridge = class {
527
1028
  constructor(token, callbacks) {
528
1029
  this.token = token;
@@ -584,7 +1085,7 @@ var TelegramBridge = class {
584
1085
  const updates = result;
585
1086
  for (const update of updates) {
586
1087
  this.offset = Math.max(this.offset, update.update_id + 1);
587
- if (update.message !== void 0) this.handleMessage(update.message);
1088
+ if (update.message !== void 0) void this.handleMessage(update.message);
588
1089
  }
589
1090
  } else {
590
1091
  this.setStatus("error", "poll failed");
@@ -592,13 +1093,53 @@ var TelegramBridge = class {
592
1093
  }
593
1094
  if (!this.stopped) this.pollTimer = setTimeout(() => void this.poll(), 0);
594
1095
  }
595
- handleMessage(m) {
1096
+ async handleMessage(m) {
596
1097
  const from = m.from;
597
1098
  if (from?.is_bot === true) return;
598
- const text = typeof m.text === "string" ? m.text.trim() : "";
599
- if (text === "") return;
600
1099
  const chat = m.chat;
601
1100
  if (chat === void 0) return;
1101
+ const caption = typeof m.caption === "string" ? m.caption.trim() : "";
1102
+ let text = typeof m.text === "string" ? m.text.trim() : "";
1103
+ if (text === "") text = caption;
1104
+ const notes = [];
1105
+ const attachments = [];
1106
+ if (Array.isArray(m.photo) && m.photo.length > 0) {
1107
+ const sizes = m.photo;
1108
+ const best = sizes.reduce((a, b) => {
1109
+ const sa = a.file_size ?? (a.width ?? 0) * (a.height ?? 0);
1110
+ const sb = b.file_size ?? (b.width ?? 0) * (b.height ?? 0);
1111
+ return sb > sa ? b : a;
1112
+ });
1113
+ if (best.file_id !== void 0) {
1114
+ const data = await this.downloadTelegramFile(best.file_id);
1115
+ if (data !== null) attachments.push({ kind: "image", data });
1116
+ else notes.push("\uFF08\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF09");
1117
+ }
1118
+ } else {
1119
+ const mediaKeys = ["animation", "document", "video", "video_note", "voice", "audio", "sticker"];
1120
+ for (const key of mediaKeys) {
1121
+ const media = m[key];
1122
+ if (media?.file_id === void 0) continue;
1123
+ const size = media.file_size ?? 0;
1124
+ if (size > TG_DOWNLOAD_LIMIT) {
1125
+ notes.push(`\uFF08${key} \u8D85\u8FC7\u5B98\u65B9 20MB \u4E0B\u8F7D\u4E0A\u9650\uFF0C\u672A\u4E0B\u8F7D\uFF09`);
1126
+ break;
1127
+ }
1128
+ const data = await this.downloadTelegramFile(media.file_id);
1129
+ if (data !== null) {
1130
+ attachments.push({ kind: "file", data, name: media.file_name, mediaType: media.mime_type });
1131
+ } else {
1132
+ notes.push(`\uFF08${key} \u4E0B\u8F7D\u5931\u8D25\uFF09`);
1133
+ }
1134
+ break;
1135
+ }
1136
+ }
1137
+ if (text === "" && attachments.length === 0 && notes.length === 0) {
1138
+ const contentKeys = ["contact", "location", "venue", "poll", "dice", "game", "forward_origin"];
1139
+ if (!contentKeys.some((k) => m[k] !== void 0)) return;
1140
+ text = "\uFF08\u6536\u5230\u8BE5\u7C7B\u578B Telegram \u6D88\u606F\uFF0C\u6682\u4E0D\u652F\u6301\u5904\u7406\uFF09";
1141
+ }
1142
+ if (text === "" && notes.length > 0) text = notes.join("\n");
602
1143
  const frame = { chatId: chat.id, messageId: m.message_id ?? 0, chatType: chat.type ?? "private" };
603
1144
  const sink = {
604
1145
  stream: (f, sid, content, finish) => void this.streamReply(f, sid, content, finish)
@@ -609,8 +1150,26 @@ var TelegramBridge = class {
609
1150
  sink,
610
1151
  chatType: (chat.type ?? "private") === "private" ? "single" : "group"
611
1152
  };
612
- console.log("[dsh-message-gateway] telegram text", { chatId: chat.id, text: text.slice(0, 60) });
613
- this.callbacks.onText(text, identity);
1153
+ console.log("[dsh-message-gateway] telegram text", { chatId: chat.id, text: text.slice(0, 60), atts: attachments.length });
1154
+ this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
1155
+ }
1156
+ /** 官方文档:getFile(file_id) → file_path → https://api.telegram.org/file/bot<token>/<file_path>。 */
1157
+ async downloadTelegramFile(fileId) {
1158
+ try {
1159
+ const result = await this.api("getFile", { file_id: fileId });
1160
+ const filePath = result?.result?.file_path;
1161
+ if (filePath === void 0 || filePath === "") return null;
1162
+ const dispatcher = await getProxyDispatcher();
1163
+ const response = await fetch(`https://api.telegram.org/file/bot${this.token}/${filePath}`, {
1164
+ signal: AbortSignal.timeout(6e4),
1165
+ ...dispatcher ? { dispatcher } : {}
1166
+ });
1167
+ if (!response.ok) return null;
1168
+ return new Uint8Array(await response.arrayBuffer());
1169
+ } catch (error) {
1170
+ console.warn("[dsh-message-gateway] telegram download failed", fileId, String(error));
1171
+ return null;
1172
+ }
614
1173
  }
615
1174
  /** 流式回复:状态合并 + 单 worker——首次 sendMessage,随后 editMessageText 渐进更新(限频)。 */
616
1175
  async streamReply(frame, streamId, content, finish) {
@@ -717,6 +1276,7 @@ var REST = "https://discord.com/api/v10";
717
1276
  var INTENTS = 1 << 0 | 1 << 9 | 1 << 12 | 1 << 15;
718
1277
  var EDIT_INTERVAL_MS2 = 1200;
719
1278
  var MSG_LIMIT2 = 2e3;
1279
+ var DISCORD_ATTACH_MAX_BYTES = 50 * 1024 * 1024;
720
1280
  var DiscordBridge = class {
721
1281
  constructor(token, callbacks) {
722
1282
  this.token = token;
@@ -799,7 +1359,7 @@ var DiscordBridge = class {
799
1359
  this.setStatus("connected", name);
800
1360
  console.log("[dsh-message-gateway] discord READY", name);
801
1361
  } else if (payload.t === "MESSAGE_CREATE") {
802
- this.handleMessage(payload.d);
1362
+ void this.handleMessage(payload.d);
803
1363
  }
804
1364
  break;
805
1365
  }
@@ -850,11 +1410,37 @@ var DiscordBridge = class {
850
1410
  clearTimeout(timer);
851
1411
  }
852
1412
  }
853
- handleMessage(d) {
1413
+ async handleMessage(d) {
854
1414
  const author = d.author;
855
1415
  if (author?.bot === true) return;
856
- const text = typeof d.content === "string" ? d.content.trim() : "";
857
- if (text === "") return;
1416
+ let text = typeof d.content === "string" ? d.content.trim() : "";
1417
+ const notes = [];
1418
+ const attachments = [];
1419
+ const rawAtts = Array.isArray(d.attachments) ? d.attachments : [];
1420
+ for (const a of rawAtts) {
1421
+ const filename = typeof a.filename === "string" ? a.filename : "\u672A\u77E5";
1422
+ const buf = await this.downloadAttachment(a);
1423
+ if (buf === null) {
1424
+ notes.push(`\uFF08\u9644\u4EF6\u300C${filename}\u300D\u4E0B\u8F7D\u5931\u8D25\uFF09`);
1425
+ continue;
1426
+ }
1427
+ const contentType = typeof a.content_type === "string" ? a.content_type : "";
1428
+ attachments.push({
1429
+ kind: contentType.startsWith("image/") ? "image" : "file",
1430
+ data: buf,
1431
+ mediaType: contentType === "" ? void 0 : contentType,
1432
+ name: filename
1433
+ });
1434
+ }
1435
+ const embeds = Array.isArray(d.embeds) ? d.embeds : [];
1436
+ for (const e of embeds) {
1437
+ const title = typeof e.title === "string" ? e.title : "";
1438
+ const url = typeof e.url === "string" ? e.url : "";
1439
+ if (title !== "" || url !== "") notes.push(`\uFF08\u5D4C\u5165\u5185\u5BB9\uFF1A${title} ${url}\uFF09`.replace(/\s+/g, " "));
1440
+ }
1441
+ if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
1442
+ ${notes.join("\n")}`;
1443
+ if (text === "" && attachments.length === 0) return;
858
1444
  const channelId = String(d.channel_id ?? "");
859
1445
  if (channelId === "") return;
860
1446
  const guildId = typeof d.guild_id === "string" ? d.guild_id : "";
@@ -868,8 +1454,39 @@ var DiscordBridge = class {
868
1454
  sink,
869
1455
  chatType: guildId === "" ? "single" : "group"
870
1456
  };
871
- console.log("[dsh-message-gateway] discord text", { channelId, text: text.slice(0, 60) });
872
- this.callbacks.onText(text, identity);
1457
+ console.log("[dsh-message-gateway] discord text", { channelId, text: text.slice(0, 60), atts: attachments.length });
1458
+ this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
1459
+ }
1460
+ /**
1461
+ * 下载附件。官方 Reference 明确要求合法的 User-Agent(否则可能被 Cloudflare 拦截);
1462
+ * CDN 是签名 URL,官方未说明是否需要 Bot 鉴权,故先不带鉴权、401/403 时带 token 重试。
1463
+ */
1464
+ async downloadAttachment(att) {
1465
+ const url = typeof att.url === "string" ? att.url : "";
1466
+ if (url === "") return null;
1467
+ const userAgent = "DiscordBot (https://github.com/a792883583/dsh-message-gateway, 1.0.0)";
1468
+ try {
1469
+ let response = await smartFetchBinary(url, { headers: { "User-Agent": userAgent }, signal: AbortSignal.timeout(6e4) });
1470
+ if (response.status === 401 || response.status === 403) {
1471
+ response = await smartFetchBinary(url, {
1472
+ headers: { "User-Agent": userAgent, authorization: `Bot ${this.token}` },
1473
+ signal: AbortSignal.timeout(6e4)
1474
+ });
1475
+ }
1476
+ if (response.status !== 200) {
1477
+ console.warn("[dsh-message-gateway] discord attachment http", response.status);
1478
+ return null;
1479
+ }
1480
+ const buf = new Uint8Array(await response.arrayBuffer());
1481
+ if (buf.byteLength > DISCORD_ATTACH_MAX_BYTES) {
1482
+ console.warn("[dsh-message-gateway] discord attachment too large", buf.byteLength);
1483
+ return null;
1484
+ }
1485
+ return buf;
1486
+ } catch (error) {
1487
+ console.warn("[dsh-message-gateway] discord attachment failed", String(error));
1488
+ return null;
1489
+ }
873
1490
  }
874
1491
  /** 流式回复:状态合并 + 单 worker——首次发送消息,随后 PATCH 渐进更新(限频)。 */
875
1492
  async streamReply(frame, streamId, content, finish) {
@@ -955,11 +1572,47 @@ var DiscordBridge = class {
955
1572
  };
956
1573
 
957
1574
  // src/host/qq-bridge.ts
1575
+ init_incoming();
958
1576
  import { createPrivateKey, sign, verify } from "node:crypto";
959
1577
  var TOKEN_URL = "https://api.bot.qq.com/app/getAppAccessToken";
960
1578
  var BASE = "https://api.bot.qq.com";
961
1579
  var INTENTS2 = 1 << 25;
962
1580
  var DEDUP_CAP = 64;
1581
+ var QQ_ATTACH_MAX_BYTES = 200 * 1024 * 1024;
1582
+ async function collectQqAttachments(node) {
1583
+ const attachments = [];
1584
+ const asrTexts = [];
1585
+ const notes = [];
1586
+ const seen = /* @__PURE__ */ new Set();
1587
+ const walk = async (item) => {
1588
+ const list = Array.isArray(item.attachments) ? item.attachments : [];
1589
+ for (const a of list) {
1590
+ const url = typeof a.url === "string" ? a.url : "";
1591
+ const name = typeof a.filename === "string" && a.filename !== "" ? a.filename : "\u672A\u77E5";
1592
+ if (typeof a.asr_refer_text === "string" && a.asr_refer_text.trim() !== "") {
1593
+ asrTexts.push(a.asr_refer_text.trim());
1594
+ }
1595
+ if (url === "" || seen.has(url)) continue;
1596
+ seen.add(url);
1597
+ try {
1598
+ const data = await downloadBytes(url, { maxBytes: QQ_ATTACH_MAX_BYTES });
1599
+ const contentType = typeof a.content_type === "string" ? a.content_type : "";
1600
+ attachments.push({
1601
+ kind: contentType.startsWith("image/") ? "image" : "file",
1602
+ data,
1603
+ mediaType: contentType === "" ? void 0 : contentType,
1604
+ name
1605
+ });
1606
+ } catch (error) {
1607
+ notes.push(`\uFF08\u9644\u4EF6\u300C${name}\u300D\u4E0B\u8F7D\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
1608
+ }
1609
+ }
1610
+ const elements = Array.isArray(item.msg_elements) ? item.msg_elements : [];
1611
+ for (const el of elements) await walk(el);
1612
+ };
1613
+ await walk(node);
1614
+ return { attachments, asrTexts, notes };
1615
+ }
963
1616
  function qqEd25519Key(secret) {
964
1617
  let seed = secret;
965
1618
  while (Buffer.byteLength(seed) < 32) seed += seed;
@@ -1201,9 +1854,9 @@ var QQBridge = class {
1201
1854
  this.setStatus("connected", "qq");
1202
1855
  console.log("[dsh-message-gateway] qq READY");
1203
1856
  } else if (payload.t === "C2C_MESSAGE_CREATE") {
1204
- this.handleMessage(payload.d, "c2c");
1857
+ void this.handleMessage(payload.d, "c2c");
1205
1858
  } else if (payload.t === "GROUP_AT_MESSAGE_CREATE") {
1206
- this.handleMessage(payload.d, "group");
1859
+ void this.handleMessage(payload.d, "group");
1207
1860
  }
1208
1861
  break;
1209
1862
  }
@@ -1271,11 +1924,10 @@ var QQBridge = class {
1271
1924
  }
1272
1925
  }
1273
1926
  /** 单聊/群聊消息分发(content 群聊已去 @前缀)。 */
1274
- handleMessage(d, scene) {
1927
+ async handleMessage(d, scene) {
1275
1928
  const author = d.author;
1276
1929
  if (author?.bot === true) return;
1277
- const text = typeof d.content === "string" ? d.content.trim() : "";
1278
- if (text === "") return;
1930
+ let text = typeof d.content === "string" ? d.content.trim() : "";
1279
1931
  const msgId = String(d.id ?? "");
1280
1932
  if (msgId === "") return;
1281
1933
  if (this.recentMsgIds.has(msgId)) return;
@@ -1286,6 +1938,12 @@ var QQBridge = class {
1286
1938
  }
1287
1939
  const openid = scene === "c2c" ? author?.user_openid ?? "" : String(d.group_openid ?? "");
1288
1940
  if (openid === "") return;
1941
+ const { attachments, asrTexts, notes } = await collectQqAttachments(d);
1942
+ if (asrTexts.length > 0) text = text === "" ? asrTexts.join("\n") : `${text}
1943
+ ${asrTexts.join("\n")}`;
1944
+ if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
1945
+ ${notes.join("\n")}`;
1946
+ if (text === "" && attachments.length === 0) return;
1289
1947
  const frame = { openid, msgId, scene };
1290
1948
  const sink = {
1291
1949
  // 单聊:流式(ack 开启,「正在处理…」就地增长);群聊:不支持流式,关闭 ack 只发定稿。
@@ -1299,8 +1957,8 @@ var QQBridge = class {
1299
1957
  sink,
1300
1958
  chatType: scene === "c2c" ? "single" : "group"
1301
1959
  };
1302
- console.log("[dsh-message-gateway] qq text", { scene, openid, text: text.slice(0, 60) });
1303
- this.callbacks.onText(text, identity);
1960
+ console.log("[dsh-message-gateway] qq text", { scene, openid, text: text.slice(0, 60), atts: attachments.length });
1961
+ this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
1304
1962
  }
1305
1963
  /** 停止网关连接。 */
1306
1964
  stop() {
@@ -1383,8 +2041,17 @@ var QqWebhookBridge = class {
1383
2041
  sink,
1384
2042
  chatType: scene === "c2c" ? "single" : "group"
1385
2043
  };
1386
- console.log("[dsh-message-gateway] qq webhook text", { scene, openid, text: text.slice(0, 60) });
1387
- this.callbacks.onText(text, identity);
2044
+ void (async () => {
2045
+ let body = typeof d.content === "string" ? d.content.trim() : "";
2046
+ const { attachments, asrTexts, notes } = await collectQqAttachments(d);
2047
+ if (asrTexts.length > 0) body = body === "" ? asrTexts.join("\n") : `${body}
2048
+ ${asrTexts.join("\n")}`;
2049
+ if (notes.length > 0) body = body === "" ? notes.join("\n") : `${body}
2050
+ ${notes.join("\n")}`;
2051
+ if (body === "" && attachments.length === 0) return;
2052
+ console.log("[dsh-message-gateway] qq webhook text", { scene, openid, text: body.slice(0, 60), atts: attachments.length });
2053
+ this.callbacks.onText(body, identity, attachments.length > 0 ? attachments : void 0);
2054
+ })();
1388
2055
  return true;
1389
2056
  }
1390
2057
  /** 确保 access_token 未过期(提前 60s 刷新)。 */
@@ -1440,6 +2107,245 @@ var QqWebhookBridge = class {
1440
2107
  // src/host/email-bridge.ts
1441
2108
  import { connect } from "node:net";
1442
2109
  import { connect as tlsConnect } from "node:tls";
2110
+
2111
+ // src/host/email-mime.ts
2112
+ function tokenize(text) {
2113
+ let i = 0;
2114
+ const parseList = () => {
2115
+ if (text[i] !== "(") return null;
2116
+ i += 1;
2117
+ const out = [];
2118
+ while (i < text.length) {
2119
+ const c = text[i];
2120
+ if (c === " " || c === "\r" || c === "\n" || c === " ") {
2121
+ i += 1;
2122
+ continue;
2123
+ }
2124
+ if (c === ")") {
2125
+ i += 1;
2126
+ return out;
2127
+ }
2128
+ if (c === "(") {
2129
+ const inner = parseList();
2130
+ if (inner === null) return null;
2131
+ out.push(inner);
2132
+ continue;
2133
+ }
2134
+ if (c === '"') {
2135
+ i += 1;
2136
+ let s = "";
2137
+ while (i < text.length && text[i] !== '"') {
2138
+ if (text[i] === "\\" && i + 1 < text.length) {
2139
+ i += 1;
2140
+ s += text[i];
2141
+ i += 1;
2142
+ continue;
2143
+ }
2144
+ s += text[i];
2145
+ i += 1;
2146
+ }
2147
+ i += 1;
2148
+ out.push(s);
2149
+ continue;
2150
+ }
2151
+ let atom = "";
2152
+ while (i < text.length && !" ()\r\n ".includes(text[i])) {
2153
+ atom += text[i];
2154
+ i += 1;
2155
+ }
2156
+ out.push(atom.toUpperCase() === "NIL" ? null : atom);
2157
+ }
2158
+ return out;
2159
+ };
2160
+ while (i < text.length && /\s/.test(text[i])) i += 1;
2161
+ return parseList();
2162
+ }
2163
+ function asParams(tok) {
2164
+ const out = {};
2165
+ if (!Array.isArray(tok)) return out;
2166
+ for (let i = 0; i + 1 < tok.length; i += 2) {
2167
+ const k = tok[i];
2168
+ const v = tok[i + 1];
2169
+ if (typeof k === "string" && typeof v === "string") out[k.toLowerCase()] = v;
2170
+ }
2171
+ return out;
2172
+ }
2173
+ function pctToBuffer(s) {
2174
+ const bytes = [];
2175
+ for (let i = 0; i < s.length; i += 1) {
2176
+ if (s[i] === "%" && i + 2 < s.length) {
2177
+ const hex = s.slice(i + 1, i + 3);
2178
+ if (/^[0-9a-fA-F]{2}$/.test(hex)) {
2179
+ bytes.push(parseInt(hex, 16));
2180
+ i += 2;
2181
+ continue;
2182
+ }
2183
+ }
2184
+ bytes.push(s.charCodeAt(i) & 255);
2185
+ }
2186
+ return Buffer.from(bytes);
2187
+ }
2188
+ function bufferToString(buf, charset) {
2189
+ const cs = charset.trim().toLowerCase();
2190
+ if (cs === "iso-8859-1" || cs === "latin1" || cs === "windows-1252") return buf.toString("latin1");
2191
+ if (cs === "us-ascii" || cs === "ascii") return buf.toString("ascii");
2192
+ return buf.toString("utf8");
2193
+ }
2194
+ function decodeRfc2231(value) {
2195
+ const m = value.match(/^([^']*)'([^']*)'(.*)$/);
2196
+ const charset = m === null ? "utf-8" : m[1];
2197
+ const encoded = m === null ? value : m[3];
2198
+ return bufferToString(pctToBuffer(encoded), charset);
2199
+ }
2200
+ function decodeEncodedWords(value) {
2201
+ return value.replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=/g, (_all, charset, enc, text) => {
2202
+ try {
2203
+ if (enc.toUpperCase() === "B") return bufferToString(Buffer.from(text, "base64"), charset);
2204
+ const qp = text.replace(/_/g, " ").replace(/=([0-9A-Fa-f]{2})/g, (_x, h) => String.fromCharCode(parseInt(h, 16)));
2205
+ return bufferToString(Buffer.from(qp, "latin1"), charset);
2206
+ } catch {
2207
+ return text;
2208
+ }
2209
+ });
2210
+ }
2211
+ function paramValue(params, base) {
2212
+ const single = params[`${base}*`];
2213
+ if (single !== void 0) return { value: single, extended: true };
2214
+ const parts = [];
2215
+ const re = new RegExp(`^${base}\\*(\\d+)(\\*)?$`);
2216
+ for (const [k, v] of Object.entries(params)) {
2217
+ const m = k.match(re);
2218
+ if (m !== null) parts.push({ i: Number(m[1]), v, ext: m[2] === "*" });
2219
+ }
2220
+ if (parts.length > 0) {
2221
+ parts.sort((a, b) => a.i - b.i);
2222
+ return { value: parts.map((p) => p.v).join(""), extended: parts[0].ext };
2223
+ }
2224
+ const plain = params[base];
2225
+ return plain === void 0 ? null : { value: plain, extended: false };
2226
+ }
2227
+ function sanitizeFilename(name) {
2228
+ const base = name.split(/[\\/]/).pop() ?? name;
2229
+ const cleaned = base.replace(/[\u0000-\u001f\u007f]/g, "").trim();
2230
+ return cleaned === "" ? "attachment" : cleaned;
2231
+ }
2232
+ function pickFilename(params) {
2233
+ for (const base of ["filename", "name"]) {
2234
+ const hit = paramValue(params, base);
2235
+ if (hit === null) continue;
2236
+ const decoded = hit.extended ? decodeRfc2231(hit.value) : decodeEncodedWords(hit.value);
2237
+ if (decoded.trim() !== "") return sanitizeFilename(decoded);
2238
+ }
2239
+ return "";
2240
+ }
2241
+ function interpret(sexp, prefix) {
2242
+ if (!Array.isArray(sexp) || sexp.length === 0) return null;
2243
+ if (Array.isArray(sexp[0])) {
2244
+ const children = [];
2245
+ let idx = 0;
2246
+ while (idx < sexp.length && Array.isArray(sexp[idx])) {
2247
+ const childPart = prefix === "" ? String(children.length + 1) : `${prefix}.${children.length + 1}`;
2248
+ const child = interpret(sexp[idx], childPart);
2249
+ if (child !== null) children.push(child);
2250
+ idx += 1;
2251
+ }
2252
+ const subtypeRaw = sexp[idx];
2253
+ const subtype2 = typeof subtypeRaw === "string" ? subtypeRaw.toLowerCase() : "mixed";
2254
+ const params2 = asParams(sexp[idx + 1]);
2255
+ return {
2256
+ part: prefix,
2257
+ type: "multipart",
2258
+ subtype: subtype2,
2259
+ params: params2,
2260
+ id: "",
2261
+ encoding: "",
2262
+ octets: 0,
2263
+ disposition: "",
2264
+ filename: "",
2265
+ children
2266
+ };
2267
+ }
2268
+ const type = typeof sexp[0] === "string" ? sexp[0].toLowerCase() : "application";
2269
+ const subtype = typeof sexp[1] === "string" ? sexp[1].toLowerCase() : "octet-stream";
2270
+ const params = asParams(sexp[2]);
2271
+ const id = typeof sexp[3] === "string" ? sexp[3].replace(/^<|>$/g, "") : "";
2272
+ const encoding = typeof sexp[5] === "string" ? sexp[5].toLowerCase() : "7bit";
2273
+ const octets = Number(sexp[6] ?? 0) || 0;
2274
+ let disposition = "";
2275
+ let dispParams = {};
2276
+ for (let i = 7; i < sexp.length; i += 1) {
2277
+ const el = sexp[i];
2278
+ if (Array.isArray(el) && el.length >= 1 && typeof el[0] === "string") {
2279
+ disposition = el[0].toLowerCase();
2280
+ dispParams = asParams(el[1]);
2281
+ break;
2282
+ }
2283
+ }
2284
+ const merged = { ...params, ...dispParams };
2285
+ return {
2286
+ part: prefix === "" ? "1" : prefix,
2287
+ type,
2288
+ subtype,
2289
+ params: merged,
2290
+ id,
2291
+ encoding,
2292
+ octets,
2293
+ disposition,
2294
+ filename: pickFilename(merged),
2295
+ children: []
2296
+ };
2297
+ }
2298
+ function parseBodyStructure(sexp) {
2299
+ const tok = tokenize(sexp);
2300
+ if (tok === null) return null;
2301
+ return interpret(tok, "");
2302
+ }
2303
+ function flattenParts(root) {
2304
+ if (root === null) return [];
2305
+ const out = [];
2306
+ const walk = (node) => {
2307
+ if (node.children.length > 0) {
2308
+ for (const c of node.children) walk(c);
2309
+ return;
2310
+ }
2311
+ out.push(node);
2312
+ };
2313
+ walk(root);
2314
+ return out;
2315
+ }
2316
+ function decodeBody(raw, encoding) {
2317
+ const enc = encoding.toLowerCase();
2318
+ if (enc === "base64") {
2319
+ return new Uint8Array(Buffer.from(raw.replace(/[^A-Za-z0-9+/=]/g, ""), "base64"));
2320
+ }
2321
+ if (enc === "quoted-printable") {
2322
+ const bytes = [];
2323
+ for (let i = 0; i < raw.length; i += 1) {
2324
+ if (raw[i] === "=") {
2325
+ if (raw[i + 1] === "\r" && raw[i + 2] === "\n") {
2326
+ i += 2;
2327
+ continue;
2328
+ }
2329
+ if (raw[i + 1] === "\n") {
2330
+ i += 1;
2331
+ continue;
2332
+ }
2333
+ const hex = raw.slice(i + 1, i + 3);
2334
+ if (/^[0-9a-fA-F]{2}$/.test(hex)) {
2335
+ bytes.push(parseInt(hex, 16));
2336
+ i += 2;
2337
+ continue;
2338
+ }
2339
+ }
2340
+ bytes.push(raw.charCodeAt(i) & 255);
2341
+ }
2342
+ return new Uint8Array(Buffer.from(bytes));
2343
+ }
2344
+ return new Uint8Array(Buffer.from(raw, "latin1"));
2345
+ }
2346
+
2347
+ // src/host/email-bridge.ts
2348
+ var EMAIL_ATTACH_MAX_BYTES = 25 * 1024 * 1024;
1443
2349
  var POLL_MS = 3e4;
1444
2350
  var RETRY_MS = 5e3;
1445
2351
  var MAX_BODY = 12e3;
@@ -1603,6 +2509,49 @@ var ImapClient = class {
1603
2509
  const text = literalAt(res, "BODY[TEXT]")?.value ?? "";
1604
2510
  return { uid, header, text };
1605
2511
  }
2512
+ /**
2513
+ * 取 BODYSTRUCTURE(RFC 3501 §6.4.5):一次拿到整棵 MIME 树,
2514
+ * 含每个 part 的类型/参数/ID/编码/字节数与 Content-Disposition,
2515
+ * 便于在下载正文前判断哪些是附件。BODY.PEEK 不置 \Seen。
2516
+ */
2517
+ async fetchStructure(id) {
2518
+ let res;
2519
+ try {
2520
+ res = await this.command(`FETCH ${id} (UID BODYSTRUCTURE)`, 3e4);
2521
+ } catch {
2522
+ return null;
2523
+ }
2524
+ const idx = res.indexOf("BODYSTRUCTURE");
2525
+ if (idx === -1) return null;
2526
+ const start = res.indexOf("(", idx);
2527
+ if (start === -1) return null;
2528
+ let depth = 0;
2529
+ for (let i = start; i < res.length; i += 1) {
2530
+ const c = res[i];
2531
+ if (c === '"') {
2532
+ i += 1;
2533
+ while (i < res.length && res[i] !== '"') {
2534
+ if (res[i] === "\\") i += 1;
2535
+ i += 1;
2536
+ }
2537
+ continue;
2538
+ }
2539
+ if (c === "(") depth += 1;
2540
+ else if (c === ")") {
2541
+ depth -= 1;
2542
+ if (depth === 0) return parseBodyStructure(res.slice(start, i + 1));
2543
+ }
2544
+ }
2545
+ return null;
2546
+ }
2547
+ /**
2548
+ * 拉取指定 part 的正文(原始编码,尚未 base64/QP 解码)。
2549
+ * RFC 3501 §6.4.5:必须用 BODY.PEEK 以免把邮件标记为已读。
2550
+ */
2551
+ async fetchPart(id, part) {
2552
+ const res = await this.command(`FETCH ${id} (BODY.PEEK[${part}])`, 6e4);
2553
+ return literalAt(res, `BODY[${part}]`)?.value ?? "";
2554
+ }
1606
2555
  async markSeen(id) {
1607
2556
  await this.command(`STORE ${id} +FLAGS (\\Seen)`);
1608
2557
  }
@@ -1901,10 +2850,52 @@ var EmailBridge = class {
1901
2850
  const threadKey = references[0] ?? (inReplyTo !== "" ? inReplyTo : messageId);
1902
2851
  const from = parseAddress(headerField(fetched.header, "From"));
1903
2852
  const subject = headerField(fetched.header, "Subject");
1904
- const text = cleanBody(fetched.text);
2853
+ const root = await this.imap.fetchStructure(id);
2854
+ const parts = flattenParts(root);
2855
+ const notes = [];
2856
+ const attachments = [];
2857
+ const textNode = parts.find((p) => p.type === "text" && p.subtype === "plain");
2858
+ let text = "";
2859
+ if (textNode !== void 0) {
2860
+ try {
2861
+ const raw = await this.imap.fetchPart(id, textNode.part);
2862
+ text = cleanBody(Buffer.from(decodeBody(raw, textNode.encoding)).toString("utf8"));
2863
+ } catch {
2864
+ notes.push("\uFF08\u6B63\u6587\u8BFB\u53D6\u5931\u8D25\uFF0C\u5DF2\u56DE\u9000\u5230\u539F\u59CB\u6B63\u6587\uFF09");
2865
+ }
2866
+ }
2867
+ if (text.trim() === "") text = cleanBody(fetched.text);
2868
+ for (const p of parts) {
2869
+ if (p === textNode) continue;
2870
+ const isAttachment = p.disposition === "attachment" || p.disposition === "" && p.filename !== "" || p.disposition !== "inline" && p.filename !== "" && p.disposition !== "attachment";
2871
+ if (!isAttachment) continue;
2872
+ if (p.filename === "") continue;
2873
+ if (p.octets > EMAIL_ATTACH_MAX_BYTES) {
2874
+ notes.push(`\uFF08\u9644\u4EF6\u300C${p.filename}\u300D\u7EA6 ${Math.round(p.octets / 1024 / 1024)}MB\uFF0C\u8D85\u8FC7\u4E0A\u9650\u672A\u4E0B\u8F7D\uFF09`);
2875
+ continue;
2876
+ }
2877
+ try {
2878
+ const raw = await this.imap.fetchPart(id, p.part);
2879
+ const data = decodeBody(raw, p.encoding);
2880
+ if (data.byteLength === 0) {
2881
+ notes.push(`\uFF08\u9644\u4EF6\u300C${p.filename}\u300D\u4E3A\u7A7A\uFF09`);
2882
+ continue;
2883
+ }
2884
+ attachments.push({
2885
+ kind: p.type === "image" ? "image" : "file",
2886
+ data,
2887
+ mediaType: p.type === "image" ? `image/${p.subtype}` : `${p.type}/${p.subtype}`,
2888
+ name: p.filename
2889
+ });
2890
+ } catch (error) {
2891
+ notes.push(`\uFF08\u9644\u4EF6\u300C${p.filename}\u300D\u8BFB\u53D6\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
2892
+ }
2893
+ }
1905
2894
  void this.imap.markSeen(id).catch(() => {
1906
2895
  });
1907
- if (from === "" || text.trim() === "") return;
2896
+ if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
2897
+ ${notes.join("\n")}`;
2898
+ if (from === "" || text.trim() === "" && attachments.length === 0) return;
1908
2899
  const frame = { from, subject, threadKey };
1909
2900
  const sink = {
1910
2901
  ack: false,
@@ -1920,8 +2911,8 @@ var EmailBridge = class {
1920
2911
  sink,
1921
2912
  chatType: "single"
1922
2913
  };
1923
- console.log("[dsh-message-gateway] email text", { from, subject: subject.slice(0, 40), len: text.length });
1924
- this.callbacks.onText(text, identity);
2914
+ console.log("[dsh-message-gateway] email text", { from, subject: subject.slice(0, 40), len: text.length, atts: attachments.length });
2915
+ this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
1925
2916
  }
1926
2917
  async sendReply(frame, content) {
1927
2918
  try {
@@ -1966,7 +2957,9 @@ function sleep(ms) {
1966
2957
  }
1967
2958
 
1968
2959
  // src/host/feishu-bridge.ts
2960
+ init_incoming();
1969
2961
  import * as lark from "@larksuiteoapi/node-sdk";
2962
+ var FEISHU_TEXT_TYPES = /* @__PURE__ */ new Set(["text"]);
1970
2963
  var FeishuBridge = class {
1971
2964
  constructor(cred, callbacks) {
1972
2965
  this.cred = cred;
@@ -2002,23 +2995,66 @@ var FeishuBridge = class {
2002
2995
  "im.message.receive_v1": async (data) => {
2003
2996
  try {
2004
2997
  const msg = data.message;
2005
- if (!msg || msg.message_type !== "text") return;
2006
- const parsedContent = JSON.parse(msg.content || "{}");
2007
- let text = parsedContent.text || "";
2008
- if (msg.chat_type === "group" && Array.isArray(msg.mentions)) {
2009
- for (const mention of msg.mentions) {
2010
- if (mention.key) {
2011
- text = text.replace(new RegExp(mention.key, "g"), "").trim();
2998
+ if (!msg) return;
2999
+ const messageId = msg.message_id;
3000
+ const messageType = msg.message_type;
3001
+ let text = "";
3002
+ const attachments = [];
3003
+ if (FEISHU_TEXT_TYPES.has(messageType)) {
3004
+ const parsedContent = JSON.parse(msg.content || "{}");
3005
+ text = parsedContent.text || "";
3006
+ if (msg.chat_type === "group" && Array.isArray(msg.mentions)) {
3007
+ for (const mention of msg.mentions) {
3008
+ if (mention.key) {
3009
+ text = text.replace(new RegExp(mention.key, "g"), "").trim();
3010
+ }
2012
3011
  }
2013
3012
  }
3013
+ } else if (messageType === "image") {
3014
+ const parsed = JSON.parse(msg.content || "{}");
3015
+ if (parsed.image_key !== void 0) {
3016
+ const data2 = await this.downloadMessageResource(messageId, parsed.image_key, "image");
3017
+ if (data2 === null) text = "\uFF08\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF09";
3018
+ else attachments.push({ kind: "image", data: data2, name: `${parsed.image_key}.img` });
3019
+ }
3020
+ } else if (messageType === "file" || messageType === "audio" || messageType === "media") {
3021
+ const parsed = JSON.parse(msg.content || "{}");
3022
+ if (parsed.file_key !== void 0) {
3023
+ const data2 = await this.downloadMessageResource(messageId, parsed.file_key, "file");
3024
+ if (data2 === null) text = "\uFF08\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25\uFF09";
3025
+ else attachments.push({ kind: "file", data: data2, name: parsed.file_name ?? `${parsed.file_key}.bin` });
3026
+ }
3027
+ } else if (messageType === "post") {
3028
+ const parsed = JSON.parse(msg.content || "{}");
3029
+ const rows = parsed.content_v2 ?? parsed.content ?? [];
3030
+ const texts = [];
3031
+ for (const row of rows) {
3032
+ for (const node of row) {
3033
+ if (node.tag === "text" && typeof node.text === "string") texts.push(node.text);
3034
+ else if (node.tag === "img" && node.image_key !== void 0) {
3035
+ const data2 = await this.downloadMessageResource(messageId, node.image_key, "image");
3036
+ if (data2 !== null) attachments.push({ kind: "image", data: data2, name: `${node.image_key}.img` });
3037
+ }
3038
+ }
3039
+ }
3040
+ text = texts.join("");
3041
+ } else if (messageType === "sticker") {
3042
+ text = "\uFF08\u6536\u5230\u8868\u60C5\u5305\u6D88\u606F\uFF1A\u98DE\u4E66\u4E0D\u652F\u6301\u4E0B\u8F7D\u8868\u60C5\u5305\u8D44\u6E90\uFF0C\u65E0\u6CD5\u5904\u7406\uFF09";
3043
+ } else {
3044
+ text = `\uFF08\u6536\u5230\u98DE\u4E66\u300C${messageType}\u300D\u7C7B\u578B\u6D88\u606F\uFF0C\u6682\u4E0D\u652F\u6301\u5904\u7406\uFF09`;
2014
3045
  }
2015
- if (text.trim() === "") return;
2016
- this.callbacks.onText(text.trim(), {
2017
- chatId: msg.chat_id,
2018
- messageId: msg.message_id,
2019
- senderId: data.sender?.sender_id?.user_id || data.sender?.sender_id?.open_id || "",
2020
- chatType: msg.chat_type === "group" ? "group" : "single"
2021
- });
3046
+ text = text.trim();
3047
+ if (text === "" && attachments.length === 0) return;
3048
+ this.callbacks.onText(
3049
+ text,
3050
+ {
3051
+ chatId: msg.chat_id,
3052
+ messageId,
3053
+ senderId: data.sender?.sender_id?.user_id || data.sender?.sender_id?.open_id || "",
3054
+ chatType: msg.chat_type === "group" ? "group" : "single"
3055
+ },
3056
+ attachments.length > 0 ? attachments : void 0
3057
+ );
2022
3058
  } catch (err) {
2023
3059
  console.error("[dsh-message-gateway] feishu message parsing error", err);
2024
3060
  }
@@ -2037,6 +3073,31 @@ var FeishuBridge = class {
2037
3073
  this.setStatus("error", error instanceof Error ? error.message : String(error));
2038
3074
  }
2039
3075
  }
3076
+ /**
3077
+ * 下载消息中的资源文件。
3078
+ *
3079
+ * 官方文档:必须使用「获取消息中的资源文件」
3080
+ * `GET /open-apis/im/v1/messages/:message_id/resources/:file_key`——
3081
+ * **不能**用 `im/v1/images/:image_key`(后者只能下载机器人自己上传的图片,
3082
+ * 下载用户发来的图会报 234008)。图片把 image_key 的值填到 file_key 位置。
3083
+ *
3084
+ * @param messageId 消息 ID
3085
+ * @param fileKey 图片传 image_key;文件/音频/视频传 file_key
3086
+ * @param type image=图片(含富文本图片);file=文件/音频/视频
3087
+ */
3088
+ async downloadMessageResource(messageId, fileKey, type) {
3089
+ if (this.client === null) return null;
3090
+ try {
3091
+ const res = await this.client.im.messageResource.get({
3092
+ params: { type },
3093
+ path: { message_id: messageId, file_key: fileKey }
3094
+ });
3095
+ return await collectStream(res.getReadableStream());
3096
+ } catch (error) {
3097
+ console.warn("[dsh-message-gateway] feishu resource download failed", fileKey, String(error));
3098
+ return null;
3099
+ }
3100
+ }
2040
3101
  /**
2041
3102
  * 回复某条消息(通过 message_id 引用回复)。
2042
3103
  */
@@ -2090,6 +3151,7 @@ var FeishuBridge = class {
2090
3151
  };
2091
3152
 
2092
3153
  // src/host/dingtalk-bridge.ts
3154
+ init_incoming();
2093
3155
  import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
2094
3156
  var DingTalkBridge = class {
2095
3157
  constructor(cred, callbacks) {
@@ -2098,6 +3160,9 @@ var DingTalkBridge = class {
2098
3160
  }
2099
3161
  client = null;
2100
3162
  started = false;
3163
+ /** 企业内部应用 accessToken 缓存(下载机器人消息文件需要)。 */
3164
+ accessToken = null;
3165
+ accessTokenExpiresAt = 0;
2101
3166
  status = { state: "idle", detail: "", connectedAt: null };
2102
3167
  setStatus(state, detail = "") {
2103
3168
  this.status = {
@@ -2128,18 +3193,58 @@ var DingTalkBridge = class {
2128
3193
  body: JSON.stringify({ status: "SUCCESS" })
2129
3194
  }
2130
3195
  });
2131
- const text = raw.text?.content?.trim() || "";
2132
- if (!text) return;
3196
+ const msgtype = raw.msgtype ?? "text";
3197
+ const robotCode = raw.robotCode ?? this.cred.robotCode ?? "";
3198
+ let text = "";
3199
+ const attachments = [];
3200
+ const notes = [];
3201
+ if (msgtype === "text") {
3202
+ text = raw.text?.content?.trim() || "";
3203
+ } else if (msgtype === "picture") {
3204
+ const downloadCode = raw.content?.downloadCode ?? "";
3205
+ const data = await this.downloadRobotFile(downloadCode, robotCode);
3206
+ if (data === null) text = "\uFF08\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF09";
3207
+ else attachments.push({ kind: "image", data, name: `dingtalk-${raw.msgId ?? Date.now()}.jpg` });
3208
+ } else if (msgtype === "richText") {
3209
+ const nodes = raw.content?.richText ?? [];
3210
+ const texts = [];
3211
+ for (const node of nodes) {
3212
+ if (typeof node.text === "string" && node.text !== "") texts.push(node.text);
3213
+ else if (node.type === "picture" && node.downloadCode !== void 0) {
3214
+ const data = await this.downloadRobotFile(node.downloadCode, robotCode);
3215
+ if (data !== null) attachments.push({ kind: "image", data, name: `dingtalk-${Date.now()}.jpg` });
3216
+ else notes.push("\uFF08\u5BCC\u6587\u672C\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF09");
3217
+ }
3218
+ }
3219
+ text = texts.join("");
3220
+ } else if (msgtype === "audio") {
3221
+ text = raw.content?.recognition?.trim() || "\uFF08\u6536\u5230\u8BED\u97F3\u6D88\u606F\uFF0C\u4F46\u5E73\u53F0\u672A\u63D0\u4F9B\u8BC6\u522B\u6587\u672C\uFF09";
3222
+ const downloadCode = raw.content?.downloadCode ?? "";
3223
+ if (downloadCode !== "") {
3224
+ const data = await this.downloadRobotFile(downloadCode, robotCode);
3225
+ if (data !== null) attachments.push({ kind: "file", data, name: `voice-${Date.now()}.bin` });
3226
+ }
3227
+ } else if (msgtype === "video" || msgtype === "file") {
3228
+ const downloadCode = raw.content?.downloadCode ?? "";
3229
+ const data = await this.downloadRobotFile(downloadCode, robotCode);
3230
+ if (data === null) notes.push(`\uFF08${msgtype === "video" ? "\u89C6\u9891" : "\u6587\u4EF6"}\u4E0B\u8F7D\u5931\u8D25\uFF0C\u6216\u8BE5\u573A\u666F\u4E0D\u652F\u6301\u63A5\u6536\uFF09`);
3231
+ else attachments.push({ kind: "file", data, name: `dingtalk-${Date.now()}.bin` });
3232
+ } else {
3233
+ text = `\uFF08\u6536\u5230\u9489\u9489\u300C${msgtype}\u300D\u7C7B\u578B\u6D88\u606F\uFF0C\u6682\u4E0D\u652F\u6301\u5904\u7406\uFF09`;
3234
+ }
3235
+ if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
3236
+ ${notes.join("\n")}`;
3237
+ if (text.trim() === "" && attachments.length === 0) return;
2133
3238
  const isGroup = raw.conversationType === "2";
2134
3239
  const sessionWebhook = raw.sessionWebhook || "";
2135
- this.callbacks.onText(text, {
3240
+ this.callbacks.onText(text.trim(), {
2136
3241
  conversationId: raw.conversationId || "",
2137
3242
  msgId: raw.msgId || downstream.headers.messageId,
2138
3243
  senderNick: raw.senderNick || "",
2139
3244
  senderStaffId: raw.senderStaffId || "",
2140
3245
  sessionWebhook,
2141
3246
  chatType: isGroup ? "group" : "single"
2142
- });
3247
+ }, attachments.length > 0 ? attachments : void 0);
2143
3248
  } catch (err) {
2144
3249
  console.error("[dsh-message-gateway] dingtalk message parsing error", err);
2145
3250
  }
@@ -2156,6 +3261,62 @@ var DingTalkBridge = class {
2156
3261
  this.setStatus("error", error instanceof Error ? error.message : String(error));
2157
3262
  }
2158
3263
  }
3264
+ /**
3265
+ * 取企业内部应用 accessToken(官方 v1.0 接口,AppKey/AppSecret)。
3266
+ * 带 60 秒提前过期的本地缓存,避免每条附件都换一次令牌。
3267
+ */
3268
+ async getAccessToken() {
3269
+ if (this.accessToken !== null && Date.now() < this.accessTokenExpiresAt) return this.accessToken;
3270
+ try {
3271
+ const response = await fetch("https://api.dingtalk.com/v1.0/oauth2/accessToken", {
3272
+ method: "POST",
3273
+ headers: { "content-type": "application/json" },
3274
+ body: JSON.stringify({ appKey: this.cred.clientId, appSecret: this.cred.clientSecret })
3275
+ });
3276
+ if (!response.ok) {
3277
+ console.warn("[dsh-message-gateway] dingtalk accessToken http", response.status);
3278
+ return null;
3279
+ }
3280
+ const body = await response.json();
3281
+ if (typeof body.accessToken !== "string" || body.accessToken === "") return null;
3282
+ this.accessToken = body.accessToken;
3283
+ this.accessTokenExpiresAt = Date.now() + Math.max(0, (body.expireIn ?? 7200) - 60) * 1e3;
3284
+ return this.accessToken;
3285
+ } catch (error) {
3286
+ console.warn("[dsh-message-gateway] dingtalk accessToken failed", String(error));
3287
+ return null;
3288
+ }
3289
+ }
3290
+ /**
3291
+ * 下载机器人接收到的消息文件。
3292
+ *
3293
+ * 官方文档两步走:
3294
+ * 1. `POST /v1.0/robot/messageFiles/download`(header `x-acs-dingtalk-access-token`,
3295
+ * body `{ downloadCode, robotCode }`)→ `{ downloadUrl }`
3296
+ * 2. GET 该 downloadUrl 取二进制(返回的文件名无扩展名,官方要求自行判断/替换)
3297
+ */
3298
+ async downloadRobotFile(downloadCode, robotCode) {
3299
+ if (downloadCode === "") return null;
3300
+ const token = await this.getAccessToken();
3301
+ if (token === null) return null;
3302
+ try {
3303
+ const response = await fetch("https://api.dingtalk.com/v1.0/robot/messageFiles/download", {
3304
+ method: "POST",
3305
+ headers: { "x-acs-dingtalk-access-token": token, "content-type": "application/json" },
3306
+ body: JSON.stringify({ downloadCode, robotCode })
3307
+ });
3308
+ if (!response.ok) {
3309
+ console.warn("[dsh-message-gateway] dingtalk file download http", response.status);
3310
+ return null;
3311
+ }
3312
+ const body = await response.json();
3313
+ if (typeof body.downloadUrl !== "string" || body.downloadUrl === "") return null;
3314
+ return await downloadBytes(body.downloadUrl, { timeoutMs: 6e4 });
3315
+ } catch (error) {
3316
+ console.warn("[dsh-message-gateway] dingtalk file download failed", String(error));
3317
+ return null;
3318
+ }
3319
+ }
2159
3320
  /**
2160
3321
  * 回复单次消息(通过 sessionWebhook 回复)。
2161
3322
  */
@@ -2194,7 +3355,13 @@ var DingTalkBridge = class {
2194
3355
  };
2195
3356
 
2196
3357
  // src/host/bridge-manager.ts
3358
+ init_wechat_ilink_bridge();
2197
3359
  var DEFAULT_MAX_CHAT_AGENTS = 40;
3360
+ var IMAGE_MEDIA_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
3361
+ function normalizeImageMediaType(mediaType) {
3362
+ const t = (mediaType ?? "").trim().toLowerCase();
3363
+ return IMAGE_MEDIA_TYPES.includes(t) ? t : null;
3364
+ }
2198
3365
  var STREAM_PUSH_INTERVAL = 600;
2199
3366
  var ACK_HEARTBEAT_INTERVAL = 4e3;
2200
3367
  var BridgeManager = class {
@@ -2445,6 +3612,8 @@ var BridgeManager = class {
2445
3612
  this.feishu = null;
2446
3613
  this.dingtalk?.stop();
2447
3614
  this.dingtalk = null;
3615
+ this.wechat?.stop();
3616
+ this.wechat = null;
2448
3617
  this.finishAllPending();
2449
3618
  const entries = [...this.agents.values()];
2450
3619
  this.agents.clear();
@@ -2461,11 +3630,61 @@ var BridgeManager = class {
2461
3630
  finishAllPending() {
2462
3631
  for (const key of [...this.pendingMap.keys()]) this.finishPending(key);
2463
3632
  }
3633
+ /**
3634
+ * 文本 + 附件 → 内容块。
3635
+ * - 图片:走 ctx.attachments.saveImage → ImageBlock(多模态直接交给模型);
3636
+ * 平台 MIME 不在受支持集合(png/jpeg/webp/gif)时退化为文件块。
3637
+ * - 其它文件:ctx.attachments.saveFile → FileBlock(请求组装时投影为
3638
+ * 「文件名 + 字节数 + 只读路径」句柄文本,Agent 可用文件工具读取处理)。
3639
+ * - 任何保存失败都会产出用户可见的占位文本,绝不静默丢弃。
3640
+ */
3641
+ async buildContentBlocks(text, attachments) {
3642
+ const blocks = [];
3643
+ if (text.trim() !== "") blocks.push({ type: "text", text });
3644
+ const list = attachments ?? [];
3645
+ if (list.length === 0) return blocks;
3646
+ const store = this.ctx.get?.("attachments");
3647
+ if (store === void 0) {
3648
+ blocks.push({ type: "text", text: "\uFF08\u6536\u5230\u9644\u4EF6\uFF0C\u4F46\u9644\u4EF6\u5B58\u50A8\u670D\u52A1\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5904\u7406\uFF09" });
3649
+ return blocks;
3650
+ }
3651
+ for (const att of list) {
3652
+ try {
3653
+ if (att.kind === "image") {
3654
+ const mediaType = normalizeImageMediaType(att.mediaType);
3655
+ if (mediaType === null) {
3656
+ const ref = await store.saveFile({ data: att.data, name: att.name });
3657
+ blocks.push({ type: "file", attachment: ref });
3658
+ } else {
3659
+ const ref = await store.saveImage({ data: att.data, mediaType, name: att.name });
3660
+ blocks.push({ type: "image", attachment: ref });
3661
+ }
3662
+ } else {
3663
+ const ref = await store.saveFile({ data: att.data, name: att.name });
3664
+ blocks.push({ type: "file", attachment: ref });
3665
+ }
3666
+ } catch (error) {
3667
+ if (att.kind === "image") {
3668
+ try {
3669
+ const ref = await store.saveFile({ data: att.data, name: att.name });
3670
+ blocks.push({ type: "file", attachment: ref });
3671
+ continue;
3672
+ } catch {
3673
+ }
3674
+ }
3675
+ blocks.push({
3676
+ type: "text",
3677
+ text: `\uFF08\u9644\u4EF6\u300C${att.name ?? "\u672A\u77E5"}\u300D\u4FDD\u5B58\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`
3678
+ });
3679
+ }
3680
+ }
3681
+ return blocks;
3682
+ }
2464
3683
  /**
2465
3684
  * 外部平台消息统一入口:命令优先,否则注入该聊天独立 agent 会话,
2466
3685
  * 回复经 sink 流式回发。所有已打通的平台共用此管线。
2467
3686
  */
2468
- async handleExternalMessage(id, rawText) {
3687
+ async handleExternalMessage(id, rawText, attachments) {
2469
3688
  if (this.disposed) return;
2470
3689
  const text = stripMention(rawText);
2471
3690
  const reply = (content) => {
@@ -2484,6 +3703,11 @@ var BridgeManager = class {
2484
3703
  }
2485
3704
  const route = this.matchRoute(id.key, text);
2486
3705
  const routedText = route !== null && route.prefix !== "" ? text.slice(route.prefix.length).trim() : text;
3706
+ const content = await this.buildContentBlocks(routedText, attachments);
3707
+ if (content.length === 0) {
3708
+ console.warn("[dsh-message-gateway] no content to send", { key: id.key });
3709
+ return;
3710
+ }
2487
3711
  const agent = await this.ensureAgentForKey(id.key, route?.rule);
2488
3712
  if (agent === null) {
2489
3713
  console.warn("[dsh-message-gateway] no dedicated agent available");
@@ -2492,7 +3716,7 @@ var BridgeManager = class {
2492
3716
  const message = {
2493
3717
  id: MessageId(`dsh-gateway-${Date.now().toString(36)}`),
2494
3718
  role: "user",
2495
- content: [{ type: "text", text: routedText }],
3719
+ content,
2496
3720
  source: { kind: "plugin", plugin: "dsh-message-gateway", form: "relay" }
2497
3721
  };
2498
3722
  const session = agent.session;
@@ -2606,7 +3830,7 @@ var BridgeManager = class {
2606
3830
  this.wecom?.stop();
2607
3831
  const bridge = new WecomBridge(cred, {
2608
3832
  onStatus: (status) => this.onStatusCallback?.(status),
2609
- onText: (rawText, frame) => {
3833
+ onText: (rawText, frame, attachments) => {
2610
3834
  const body = frame.body ?? {};
2611
3835
  const chattype = body.chattype ?? "single";
2612
3836
  const userid = body.from?.userid ?? "";
@@ -2617,7 +3841,7 @@ var BridgeManager = class {
2617
3841
  // 企业微信走单一流式消息(ack → 内容 → 定稿同一条消息就地更新);
2618
3842
  // 不再叠加 response_url 投递,避免出现重复消息。
2619
3843
  };
2620
- void this.handleExternalMessage({ key, frame, sink, chatType: chattype === "group" ? "group" : "single" }, rawText);
3844
+ void this.handleExternalMessage({ key, frame, sink, chatType: chattype === "group" ? "group" : "single" }, rawText, attachments);
2621
3845
  },
2622
3846
  onEnter: (frame) => {
2623
3847
  if (!this.config.welcomeReply) return;
@@ -2912,6 +4136,29 @@ ${secret}`;
2912
4136
  email = null;
2913
4137
  feishu = null;
2914
4138
  dingtalk = null;
4139
+ wechat = null;
4140
+ /** 启动微信智能机器人桥(腾讯 iLink 官方协议长轮询)。 */
4141
+ startWechat(cred) {
4142
+ this.wechat?.stop();
4143
+ const ilinkCred = {
4144
+ botToken: cred.botToken ?? "",
4145
+ baseUrl: cred.baseUrl,
4146
+ botId: cred.botId,
4147
+ userId: cred.userId,
4148
+ nickname: cred.nickname
4149
+ };
4150
+ const bridge = new WechatIlinkBridge(ilinkCred, {
4151
+ onStatus: (status) => this.onStatusCallback?.(status),
4152
+ onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
4153
+ });
4154
+ this.wechat = bridge;
4155
+ bridge.start();
4156
+ }
4157
+ /** 停止微信桥。 */
4158
+ stopWechat() {
4159
+ this.wechat?.stop();
4160
+ this.wechat = null;
4161
+ }
2915
4162
  /** 启动 DingTalk 桥(企业自建应用 Stream 模式 WebSocket 长连接)。 */
2916
4163
  startDingTalk(cred) {
2917
4164
  this.dingtalk?.stop();
@@ -2919,7 +4166,7 @@ ${secret}`;
2919
4166
  { clientId: cred.clientId ?? "", clientSecret: cred.clientSecret ?? "", robotCode: cred.robotCode },
2920
4167
  {
2921
4168
  onStatus: (status) => this.onStatusCallback?.(status),
2922
- onText: (text, frame) => {
4169
+ onText: (text, frame, attachments) => {
2923
4170
  const identity = {
2924
4171
  key: `dingtalk:${frame.conversationId}`,
2925
4172
  frame,
@@ -2933,7 +4180,7 @@ ${secret}`;
2933
4180
  },
2934
4181
  chatType: frame.chatType
2935
4182
  };
2936
- void this.handleExternalMessage(identity, text);
4183
+ void this.handleExternalMessage(identity, text, attachments);
2937
4184
  }
2938
4185
  }
2939
4186
  );
@@ -2952,7 +4199,7 @@ ${secret}`;
2952
4199
  { appId: cred.appId ?? "", appSecret: cred.appSecret ?? "" },
2953
4200
  {
2954
4201
  onStatus: (status) => this.onStatusCallback?.(status),
2955
- onText: (text, frame) => {
4202
+ onText: (text, frame, attachments) => {
2956
4203
  const identity = {
2957
4204
  key: `feishu:${frame.chatId}`,
2958
4205
  frame,
@@ -2966,7 +4213,7 @@ ${secret}`;
2966
4213
  },
2967
4214
  chatType: frame.chatType
2968
4215
  };
2969
- void this.handleExternalMessage(identity, text);
4216
+ void this.handleExternalMessage(identity, text, attachments);
2970
4217
  }
2971
4218
  }
2972
4219
  );
@@ -2983,7 +4230,7 @@ ${secret}`;
2983
4230
  this.telegram?.stop();
2984
4231
  const bridge = new TelegramBridge(cred.token ?? "", {
2985
4232
  onStatus: (status) => this.onStatusCallback?.(status),
2986
- onText: (text, identity) => void this.handleExternalMessage(identity, text)
4233
+ onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
2987
4234
  });
2988
4235
  this.telegram = bridge;
2989
4236
  bridge.start();
@@ -2998,7 +4245,7 @@ ${secret}`;
2998
4245
  this.discord?.stop();
2999
4246
  const bridge = new DiscordBridge(cred.token ?? "", {
3000
4247
  onStatus: (status) => this.onStatusCallback?.(status),
3001
- onText: (text, identity) => void this.handleExternalMessage(identity, text)
4248
+ onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
3002
4249
  });
3003
4250
  this.discord = bridge;
3004
4251
  bridge.start();
@@ -3013,7 +4260,7 @@ ${secret}`;
3013
4260
  this.qq?.stop();
3014
4261
  const bridge = new QQBridge(cred.appId ?? "", cred.secret ?? "", {
3015
4262
  onStatus: (status) => this.onStatusCallback?.(status),
3016
- onText: (text, identity) => void this.handleExternalMessage(identity, text)
4263
+ onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
3017
4264
  });
3018
4265
  this.qq = bridge;
3019
4266
  bridge.start();
@@ -3038,7 +4285,7 @@ ${secret}`;
3038
4285
  };
3039
4286
  const bridge = new EmailBridge(emailCred, {
3040
4287
  onStatus: (status) => this.onStatusCallback?.(status),
3041
- onText: (text, identity) => void this.handleExternalMessage(identity, text)
4288
+ onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
3042
4289
  });
3043
4290
  this.email = bridge;
3044
4291
  bridge.start();
@@ -3056,6 +4303,7 @@ ${secret}`;
3056
4303
  if (id === "email") return this.email?.status ?? { state: "idle", detail: "", connectedAt: null };
3057
4304
  if (id === "feishu") return this.feishu?.status ?? { state: "idle", detail: "", connectedAt: null };
3058
4305
  if (id === "dingtalk") return this.dingtalk?.status ?? { state: "idle", detail: "", connectedAt: null };
4306
+ if (id === "wechat") return this.wechat?.status ?? { state: "idle", detail: "", connectedAt: null };
3059
4307
  return { state: "idle", detail: "", connectedAt: null };
3060
4308
  }
3061
4309
  /** 将桥状态并入存储状态。 */
@@ -3131,7 +4379,8 @@ ${secret}`;
3131
4379
  bridgeLine("QQ", this.bridgeStatus("qq")),
3132
4380
  bridgeLine("Email", this.bridgeStatus("email")),
3133
4381
  bridgeLine("Feishu", this.bridgeStatus("feishu")),
3134
- bridgeLine("DingTalk", this.bridgeStatus("dingtalk"))
4382
+ bridgeLine("DingTalk", this.bridgeStatus("dingtalk")),
4383
+ bridgeLine("WeChat", this.bridgeStatus("wechat"))
3135
4384
  ];
3136
4385
  reply(lines.join("\n"));
3137
4386
  return true;
@@ -3237,10 +4486,7 @@ var PLATFORMS = [
3237
4486
  icon: "\u{1F49A}",
3238
4487
  testable: false,
3239
4488
  hintKey: "platform.wechat.hint",
3240
- fields: [
3241
- { key: "gatewayUrl", labelKey: "field.gatewayUrl", placeholderKey: "field.gatewayUrl.ph", kind: "text" },
3242
- { key: "token", labelKey: "field.token", placeholderKey: "field.secret.ph", kind: "secret" }
3243
- ]
4489
+ fields: []
3244
4490
  },
3245
4491
  {
3246
4492
  id: "wechat-mp",
@@ -3853,10 +5099,10 @@ async function buildView(manager) {
3853
5099
  for (const def of PLATFORMS) {
3854
5100
  const stored = store.statuses[def.id];
3855
5101
  const configured = store.platforms[def.id] !== void 0;
3856
- let state = configured ? stored?.state ?? "none" : def.id === "wechat" || def.id === "webhooks" ? "manual" : "none";
5102
+ let state = configured ? stored?.state ?? "none" : def.id === "webhooks" ? "manual" : "none";
3857
5103
  let detail = configured ? stored?.detail ?? "" : "";
3858
5104
  let testedAt = configured ? stored?.testedAt ?? null : null;
3859
- if (configured && (def.id === "wecom-aibot" || def.id === "telegram" || def.id === "discord" || def.id === "qq" || def.id === "email" || def.id === "feishu" || def.id === "dingtalk")) {
5105
+ if (configured && (def.id === "wecom-aibot" || def.id === "telegram" || def.id === "discord" || def.id === "qq" || def.id === "email" || def.id === "feishu" || def.id === "dingtalk" || def.id === "wechat")) {
3860
5106
  const merged = manager.mergeStatus(stored, def.id);
3861
5107
  state = merged.state;
3862
5108
  detail = merged.detail;
@@ -4189,6 +5435,49 @@ function registerGatewayRoutes(ctx, manager) {
4189
5435
  json(res, { ok: true, value: await buildView(manager) });
4190
5436
  return;
4191
5437
  }
5438
+ if (path === "/gateway/wechat/qr") {
5439
+ try {
5440
+ const { WechatIlinkBridge: WechatIlinkBridge2 } = await Promise.resolve().then(() => (init_wechat_ilink_bridge(), wechat_ilink_bridge_exports));
5441
+ const qr = await WechatIlinkBridge2.getLoginQr();
5442
+ json(res, { ok: true, value: qr });
5443
+ } catch (e) {
5444
+ json(res, { ok: false, error: { code: "internal", message: e instanceof Error ? e.message : String(e) } });
5445
+ }
5446
+ return;
5447
+ }
5448
+ if (path === "/gateway/wechat/qr-status") {
5449
+ const body = payload;
5450
+ const qrcode = body?.qrcode ?? "";
5451
+ if (!qrcode) {
5452
+ json(res, { ok: false, error: { code: "internal", message: "missing qrcode" } });
5453
+ return;
5454
+ }
5455
+ try {
5456
+ const { WechatIlinkBridge: WechatIlinkBridge2 } = await Promise.resolve().then(() => (init_wechat_ilink_bridge(), wechat_ilink_bridge_exports));
5457
+ const status = await WechatIlinkBridge2.pollQrStatus(qrcode);
5458
+ if (status.status === "confirmed" && status.botToken) {
5459
+ const store = await loadStore();
5460
+ const cred = {
5461
+ botToken: status.botToken,
5462
+ baseUrl: status.baseUrl ?? "",
5463
+ botId: status.botId ?? "",
5464
+ userId: status.userId ?? ""
5465
+ };
5466
+ store.platforms.wechat = cred;
5467
+ store.statuses.wechat = {
5468
+ state: "connected",
5469
+ detail: status.userId ? `@${status.userId}` : "\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA",
5470
+ testedAt: Date.now()
5471
+ };
5472
+ await saveStore(store);
5473
+ manager.startWechat(cred);
5474
+ }
5475
+ json(res, { ok: true, value: status });
5476
+ } catch (e) {
5477
+ json(res, { ok: false, error: { code: "internal", message: e instanceof Error ? e.message : String(e) } });
5478
+ }
5479
+ return;
5480
+ }
4192
5481
  if (path === "/gateway/save" || path === "/gateway/delete" || path === "/gateway/test") {
4193
5482
  const platform = payload?.platform;
4194
5483
  if (typeof platform !== "string") {
@@ -4207,6 +5496,7 @@ function registerGatewayRoutes(ctx, manager) {
4207
5496
  if (platform === "email") manager.stopEmail();
4208
5497
  if (platform === "feishu") manager.stopFeishu();
4209
5498
  if (platform === "dingtalk") manager.stopDingTalk();
5499
+ if (platform === "wechat") manager.stopWechat();
4210
5500
  json(res, { ok: true, value: await buildView(manager) });
4211
5501
  return;
4212
5502
  }
@@ -4263,6 +5553,13 @@ function registerGatewayRoutes(ctx, manager) {
4263
5553
  manager.stopDingTalk();
4264
5554
  }
4265
5555
  }
5556
+ if (platform === "wechat") {
5557
+ if (credentials2.botToken !== void 0 && credentials2.botToken !== "") {
5558
+ manager.startWechat(credentials2);
5559
+ } else {
5560
+ manager.stopWechat();
5561
+ }
5562
+ }
4266
5563
  json(res, { ok: true, value: await buildView(manager) });
4267
5564
  return;
4268
5565
  }
@@ -4368,6 +5665,11 @@ function apply(ctx, config = Config({})) {
4368
5665
  manager.startDingTalk(dingtalk);
4369
5666
  console.log("[dsh-message-gateway] dingtalk bridge auto-started");
4370
5667
  }
5668
+ const wechat = store.platforms.wechat;
5669
+ if (wechat !== void 0 && wechat.botToken !== "" && wechat.botToken !== void 0) {
5670
+ manager.startWechat(wechat);
5671
+ console.log("[dsh-message-gateway] wechat bridge auto-started");
5672
+ }
4371
5673
  });
4372
5674
  const disposeRoutes = registerGatewayRoutes(ctx, manager);
4373
5675
  let disposeTools;