@elizaos/plugin-wechat 2.0.0-alpha.537
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -0
- package/dist/bot.d.ts +25 -0
- package/dist/bot.js +49 -0
- package/dist/callback-server.js +207 -0
- package/dist/channel.d.ts +28 -0
- package/dist/channel.js +194 -0
- package/dist/index.d.ts +173 -0
- package/dist/index.js +833 -0
- package/dist/proxy-client.d.ts +35 -0
- package/dist/proxy-client.js +117 -0
- package/dist/reply-dispatcher.d.ts +17 -0
- package/dist/reply-dispatcher.js +47 -0
- package/dist/runtime-bridge.d.ts +12 -0
- package/dist/runtime-bridge.js +159 -0
- package/dist/types.d.ts +61 -0
- package/dist/utils/qrcode.js +20 -0
- package/package.json +65 -0
- package/src/bot.ts +95 -0
- package/src/callback-server.test.ts +190 -0
- package/src/callback-server.ts +283 -0
- package/src/channel.test.ts +121 -0
- package/src/channel.ts +314 -0
- package/src/index.ts +100 -0
- package/src/proxy-client-429.test.ts +24 -0
- package/src/proxy-client.test.ts +46 -0
- package/src/proxy-client.ts +189 -0
- package/src/reply-dispatcher.ts +75 -0
- package/src/runtime-bridge.test.ts +135 -0
- package/src/runtime-bridge.ts +259 -0
- package/src/types.ts +76 -0
- package/src/utils/qrcode.ts +16 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,833 @@
|
|
|
1
|
+
import { timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { stringToUuid } from "@elizaos/core";
|
|
4
|
+
|
|
5
|
+
//#region src/bot.ts
|
|
6
|
+
const DEFAULT_DEDUP_WINDOW_MS = 1800 * 1e3;
|
|
7
|
+
const DEDUP_MAX_ENTRIES = 1e3;
|
|
8
|
+
const DEDUP_CLEANUP_INTERVAL_MS = 300 * 1e3;
|
|
9
|
+
var Bot = class {
|
|
10
|
+
seen = /* @__PURE__ */ new Map();
|
|
11
|
+
onMessage;
|
|
12
|
+
featuresGroups;
|
|
13
|
+
featuresImages;
|
|
14
|
+
dedupWindowMs;
|
|
15
|
+
cleanupTimer = null;
|
|
16
|
+
constructor(options) {
|
|
17
|
+
this.onMessage = options.onMessage;
|
|
18
|
+
this.featuresGroups = options.featuresGroups ?? true;
|
|
19
|
+
this.featuresImages = options.featuresImages ?? true;
|
|
20
|
+
this.dedupWindowMs = options.dedupWindowMs ?? DEFAULT_DEDUP_WINDOW_MS;
|
|
21
|
+
this.cleanupTimer = setInterval(() => this.cleanup(), DEDUP_CLEANUP_INTERVAL_MS);
|
|
22
|
+
}
|
|
23
|
+
handleIncoming(message) {
|
|
24
|
+
if (this.isDuplicate(message.id)) return;
|
|
25
|
+
if (message.group && !this.featuresGroups) return;
|
|
26
|
+
if (message.type === "image" && !this.featuresImages) return;
|
|
27
|
+
if (message.type === "unknown") return;
|
|
28
|
+
Promise.resolve(this.onMessage(message)).catch((error) => {
|
|
29
|
+
console.error("[wechat] Failed to process inbound message:", error);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
isDuplicate(messageId) {
|
|
33
|
+
const now = Date.now();
|
|
34
|
+
if (this.seen.has(messageId)) return true;
|
|
35
|
+
if (this.seen.size >= DEDUP_MAX_ENTRIES) this.cleanup();
|
|
36
|
+
this.seen.set(messageId, now);
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
cleanup() {
|
|
40
|
+
const cutoff = Date.now() - this.dedupWindowMs;
|
|
41
|
+
for (const [id, ts] of this.seen) if (ts < cutoff) this.seen.delete(id);
|
|
42
|
+
}
|
|
43
|
+
stop() {
|
|
44
|
+
if (this.cleanupTimer) {
|
|
45
|
+
clearInterval(this.cleanupTimer);
|
|
46
|
+
this.cleanupTimer = null;
|
|
47
|
+
}
|
|
48
|
+
this.seen.clear();
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region src/callback-server.ts
|
|
54
|
+
const WECHAT_TYPE_MAP = {
|
|
55
|
+
60001: {
|
|
56
|
+
type: "text",
|
|
57
|
+
scope: "private"
|
|
58
|
+
},
|
|
59
|
+
60002: {
|
|
60
|
+
type: "image",
|
|
61
|
+
scope: "private"
|
|
62
|
+
},
|
|
63
|
+
60003: {
|
|
64
|
+
type: "voice",
|
|
65
|
+
scope: "private"
|
|
66
|
+
},
|
|
67
|
+
60004: {
|
|
68
|
+
type: "video",
|
|
69
|
+
scope: "private"
|
|
70
|
+
},
|
|
71
|
+
60005: {
|
|
72
|
+
type: "file",
|
|
73
|
+
scope: "private"
|
|
74
|
+
},
|
|
75
|
+
80001: {
|
|
76
|
+
type: "text",
|
|
77
|
+
scope: "group"
|
|
78
|
+
},
|
|
79
|
+
80002: {
|
|
80
|
+
type: "image",
|
|
81
|
+
scope: "group"
|
|
82
|
+
},
|
|
83
|
+
80003: {
|
|
84
|
+
type: "voice",
|
|
85
|
+
scope: "group"
|
|
86
|
+
},
|
|
87
|
+
80004: {
|
|
88
|
+
type: "video",
|
|
89
|
+
scope: "group"
|
|
90
|
+
},
|
|
91
|
+
80005: {
|
|
92
|
+
type: "file",
|
|
93
|
+
scope: "group"
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
const DEFAULT_MAX_REQUEST_BODY_BYTES = 1024 * 1024;
|
|
97
|
+
async function startCallbackServer(options) {
|
|
98
|
+
const { port, accounts, onMessage, signal, maxBodyBytes = DEFAULT_MAX_REQUEST_BODY_BYTES } = options;
|
|
99
|
+
const server = createServer((req, res) => {
|
|
100
|
+
const account = resolveWebhookAccount(req.url, accounts);
|
|
101
|
+
if (req.method !== "POST" || !account) {
|
|
102
|
+
res.writeHead(404);
|
|
103
|
+
res.end("Not Found");
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
const incomingKey = readHeaderValue(req.headers["x-api-key"]);
|
|
107
|
+
if (!incomingKey || !safeCompare(incomingKey, account.apiKey)) {
|
|
108
|
+
res.writeHead(401);
|
|
109
|
+
res.end("Unauthorized");
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
let body = "";
|
|
113
|
+
let bodyBytes = 0;
|
|
114
|
+
req.on("data", (chunk) => {
|
|
115
|
+
bodyBytes += chunk.length;
|
|
116
|
+
if (bodyBytes > maxBodyBytes) {
|
|
117
|
+
res.writeHead(413);
|
|
118
|
+
res.end("Payload Too Large");
|
|
119
|
+
req.destroy();
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
body += chunk.toString();
|
|
123
|
+
});
|
|
124
|
+
req.on("end", () => {
|
|
125
|
+
if (res.writableEnded) return;
|
|
126
|
+
try {
|
|
127
|
+
const message = normalizePayload(JSON.parse(body));
|
|
128
|
+
if (message) onMessage(account.accountId, message);
|
|
129
|
+
res.writeHead(200);
|
|
130
|
+
res.end("OK");
|
|
131
|
+
} catch {
|
|
132
|
+
res.writeHead(400);
|
|
133
|
+
res.end("Bad Request");
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
req.on("error", () => {
|
|
137
|
+
if (res.writableEnded) return;
|
|
138
|
+
res.writeHead(400);
|
|
139
|
+
res.end("Bad Request");
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
await new Promise((resolve, reject) => {
|
|
143
|
+
const handleListening = () => {
|
|
144
|
+
server.off("error", handleError);
|
|
145
|
+
resolve();
|
|
146
|
+
};
|
|
147
|
+
const handleError = (error) => {
|
|
148
|
+
server.off("listening", handleListening);
|
|
149
|
+
reject(error);
|
|
150
|
+
};
|
|
151
|
+
server.once("listening", handleListening);
|
|
152
|
+
server.once("error", handleError);
|
|
153
|
+
server.listen(port);
|
|
154
|
+
});
|
|
155
|
+
const listeningPort = server.address()?.port ?? port;
|
|
156
|
+
console.log(`[wechat] Webhook server listening on port ${listeningPort}`);
|
|
157
|
+
server.on("error", (err) => {
|
|
158
|
+
if (err.code === "EADDRINUSE") console.error(`[wechat] Port ${listeningPort} already in use — webhook server failed to start`);
|
|
159
|
+
else console.error(`[wechat] Webhook server error:`, err);
|
|
160
|
+
});
|
|
161
|
+
if (signal) signal.addEventListener("abort", () => {
|
|
162
|
+
closeServer(server);
|
|
163
|
+
}, { once: true });
|
|
164
|
+
return {
|
|
165
|
+
close: () => closeServer(server),
|
|
166
|
+
port: listeningPort
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function resolveWebhookAccount(rawUrl, accounts) {
|
|
170
|
+
if (!rawUrl) return null;
|
|
171
|
+
const pathname = new URL(rawUrl, "http://localhost").pathname;
|
|
172
|
+
if (pathname === "/webhook/wechat" && accounts.length === 1) return accounts[0];
|
|
173
|
+
const match = /^\/webhook\/wechat\/([^/]+)$/.exec(pathname);
|
|
174
|
+
if (!match) return null;
|
|
175
|
+
const accountId = decodeURIComponent(match[1]);
|
|
176
|
+
return accounts.find((account) => account.accountId === accountId) ?? null;
|
|
177
|
+
}
|
|
178
|
+
function readHeaderValue(value) {
|
|
179
|
+
if (Array.isArray(value)) return value[0];
|
|
180
|
+
return value;
|
|
181
|
+
}
|
|
182
|
+
function safeCompare(a, b) {
|
|
183
|
+
const bufA = Buffer.from(a);
|
|
184
|
+
const bufB = Buffer.from(b);
|
|
185
|
+
if (bufA.length !== bufB.length) {
|
|
186
|
+
timingSafeEqual(bufA, bufA);
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
return timingSafeEqual(bufA, bufB);
|
|
190
|
+
}
|
|
191
|
+
function closeServer(server) {
|
|
192
|
+
if (!server.listening) return Promise.resolve();
|
|
193
|
+
return new Promise((resolve, reject) => {
|
|
194
|
+
server.close((error) => {
|
|
195
|
+
if (error) {
|
|
196
|
+
reject(error);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
resolve();
|
|
200
|
+
});
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
function normalizePayload(payload) {
|
|
204
|
+
const data = payload.data ?? (payload.content ? payload : null);
|
|
205
|
+
if (!data) {
|
|
206
|
+
console.warn("[wechat] Unrecognized webhook payload format");
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
const typeCode = Number(data.type ?? data.msgType ?? 0);
|
|
210
|
+
const mapping = WECHAT_TYPE_MAP[typeCode];
|
|
211
|
+
let msgType = "unknown";
|
|
212
|
+
let scope = "private";
|
|
213
|
+
if (mapping) {
|
|
214
|
+
msgType = mapping.type;
|
|
215
|
+
scope = mapping.scope;
|
|
216
|
+
} else if (typeCode >= 60006 && typeCode <= 60010) {
|
|
217
|
+
msgType = "file";
|
|
218
|
+
scope = "private";
|
|
219
|
+
} else if (typeCode >= 80006 && typeCode <= 80010) {
|
|
220
|
+
msgType = "file";
|
|
221
|
+
scope = "group";
|
|
222
|
+
}
|
|
223
|
+
if (msgType === "unknown") {
|
|
224
|
+
console.warn(`[wechat] Unknown message type code: ${typeCode}`);
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
const sender = String(data.sender ?? data.from ?? "");
|
|
228
|
+
const recipient = String(data.recipient ?? data.to ?? "");
|
|
229
|
+
const content = String(data.content ?? data.text ?? "");
|
|
230
|
+
const timestamp = Number(data.timestamp ?? Date.now());
|
|
231
|
+
const msgId = String(data.msgId ?? data.id ?? `${sender}-${timestamp}`);
|
|
232
|
+
const isGroup = scope === "group" || sender.includes("@chatroom");
|
|
233
|
+
const threadId = isGroup ? String(data.roomId ?? data.threadId ?? sender) : void 0;
|
|
234
|
+
const groupSubject = isGroup ? String(data.roomName ?? data.groupName ?? threadId ?? "") : void 0;
|
|
235
|
+
const imageUrl = new Set([
|
|
236
|
+
"image",
|
|
237
|
+
"voice",
|
|
238
|
+
"video",
|
|
239
|
+
"file"
|
|
240
|
+
]).has(msgType) ? String(data.imageUrl ?? data.mediaUrl ?? data.url ?? data.fileUrl ?? "") : void 0;
|
|
241
|
+
return {
|
|
242
|
+
id: msgId,
|
|
243
|
+
type: msgType,
|
|
244
|
+
sender,
|
|
245
|
+
recipient,
|
|
246
|
+
content,
|
|
247
|
+
timestamp,
|
|
248
|
+
threadId,
|
|
249
|
+
group: groupSubject ? { subject: groupSubject } : void 0,
|
|
250
|
+
imageUrl: imageUrl || void 0,
|
|
251
|
+
raw: payload
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
//#endregion
|
|
256
|
+
//#region src/proxy-client.ts
|
|
257
|
+
const SUCCESS = 1e3;
|
|
258
|
+
const LOGIN_NEEDED = 1001;
|
|
259
|
+
const REQUEST_TIMEOUT_MS = 3e4;
|
|
260
|
+
var ProxyClient = class {
|
|
261
|
+
apiKey;
|
|
262
|
+
baseUrl;
|
|
263
|
+
accountId;
|
|
264
|
+
deviceType;
|
|
265
|
+
constructor(account) {
|
|
266
|
+
this.apiKey = account.apiKey;
|
|
267
|
+
this.baseUrl = normalizeProxyUrl(account.proxyUrl);
|
|
268
|
+
this.accountId = account.id;
|
|
269
|
+
this.deviceType = account.deviceType ?? "ipad";
|
|
270
|
+
}
|
|
271
|
+
async request(path, body) {
|
|
272
|
+
const url = `${this.baseUrl}${path}`;
|
|
273
|
+
const headers = {
|
|
274
|
+
"Content-Type": "application/json",
|
|
275
|
+
"X-API-Key": this.apiKey,
|
|
276
|
+
"X-Account-ID": this.accountId,
|
|
277
|
+
"X-Device-Type": this.deviceType
|
|
278
|
+
};
|
|
279
|
+
let lastError;
|
|
280
|
+
for (let attempt = 0; attempt < 3; attempt++) try {
|
|
281
|
+
const res = await fetch(url, {
|
|
282
|
+
method: "POST",
|
|
283
|
+
headers,
|
|
284
|
+
body: body ? JSON.stringify(body) : void 0,
|
|
285
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
286
|
+
});
|
|
287
|
+
if (res.status === 429) {
|
|
288
|
+
const retryAfter = res.headers.get("Retry-After");
|
|
289
|
+
const delay = retryAfter ? Number.parseInt(retryAfter, 10) * 1e3 : Math.min(1e3 * 2 ** attempt, 8e3);
|
|
290
|
+
await res.text().catch(() => {});
|
|
291
|
+
await sleep$1(delay);
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
return await res.json();
|
|
295
|
+
} catch (err) {
|
|
296
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
297
|
+
await sleep$1(Math.min(1e3 * 2 ** attempt, 8e3));
|
|
298
|
+
}
|
|
299
|
+
throw lastError ?? /* @__PURE__ */ new Error(`Request failed after 3 attempts: ${path}`);
|
|
300
|
+
}
|
|
301
|
+
async getStatus() {
|
|
302
|
+
const res = await this.request("/api/status");
|
|
303
|
+
if (res.code === LOGIN_NEEDED) return {
|
|
304
|
+
valid: true,
|
|
305
|
+
loginState: "waiting"
|
|
306
|
+
};
|
|
307
|
+
if (res.code !== SUCCESS && res.code !== 1002) throw new Error(`getStatus failed: ${res.message ?? res.code}`);
|
|
308
|
+
return requireData(res, "getStatus");
|
|
309
|
+
}
|
|
310
|
+
async getQRCode() {
|
|
311
|
+
const res = await this.request("/api/qrcode");
|
|
312
|
+
if (res.code !== SUCCESS) throw new Error(`getQRCode failed: ${res.message ?? res.code}`);
|
|
313
|
+
return requireData(res, "getQRCode").qrCodeUrl;
|
|
314
|
+
}
|
|
315
|
+
async checkLogin() {
|
|
316
|
+
const res = await this.request("/api/check-login");
|
|
317
|
+
if (res.code !== SUCCESS && res.code !== 1002) throw new Error(`checkLogin failed: ${res.message ?? res.code}`);
|
|
318
|
+
return requireData(res, "checkLogin");
|
|
319
|
+
}
|
|
320
|
+
async sendText(to, text) {
|
|
321
|
+
const res = await this.request("/api/send-text", {
|
|
322
|
+
to,
|
|
323
|
+
text
|
|
324
|
+
});
|
|
325
|
+
if (res.code === LOGIN_NEEDED) throw new LoginExpiredError();
|
|
326
|
+
if (res.code !== SUCCESS && res.code !== 1002) throw new Error(`sendText failed: ${res.message ?? res.code}`);
|
|
327
|
+
}
|
|
328
|
+
async sendImage(to, imagePath, text) {
|
|
329
|
+
const res = await this.request("/api/send-image", {
|
|
330
|
+
to,
|
|
331
|
+
imagePath,
|
|
332
|
+
text
|
|
333
|
+
});
|
|
334
|
+
if (res.code === LOGIN_NEEDED) throw new LoginExpiredError();
|
|
335
|
+
if (res.code !== SUCCESS && res.code !== 1002) throw new Error(`sendImage failed: ${res.message ?? res.code}`);
|
|
336
|
+
}
|
|
337
|
+
async getContacts() {
|
|
338
|
+
const res = await this.request("/api/contacts");
|
|
339
|
+
if (res.code !== SUCCESS) throw new Error(`getContacts failed: ${res.message ?? res.code}`);
|
|
340
|
+
return requireData(res, "getContacts");
|
|
341
|
+
}
|
|
342
|
+
async registerWebhook(url) {
|
|
343
|
+
const res = await this.request("/api/webhook/register", { webhookUrl: url });
|
|
344
|
+
if (res.code !== SUCCESS && res.code !== 1002) throw new Error(`registerWebhook failed: ${res.message ?? res.code}`);
|
|
345
|
+
}
|
|
346
|
+
get needsLogin() {
|
|
347
|
+
return false;
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
var LoginExpiredError = class extends Error {
|
|
351
|
+
constructor() {
|
|
352
|
+
super("WeChat login expired — re-login required");
|
|
353
|
+
this.name = "LoginExpiredError";
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
function sleep$1(ms) {
|
|
357
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
358
|
+
}
|
|
359
|
+
function normalizeProxyUrl(proxyUrl) {
|
|
360
|
+
const parsed = new URL(proxyUrl);
|
|
361
|
+
if (parsed.protocol !== "https:") throw new Error("[wechat] proxyUrl must use https://");
|
|
362
|
+
if (parsed.username || parsed.password) throw new Error("[wechat] proxyUrl must not include credentials");
|
|
363
|
+
parsed.hash = "";
|
|
364
|
+
return parsed.toString().replace(/\/$/, "");
|
|
365
|
+
}
|
|
366
|
+
function requireData(response, action) {
|
|
367
|
+
if (response.data === void 0) throw new Error(`${action} failed: missing response data`);
|
|
368
|
+
return response.data;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
//#endregion
|
|
372
|
+
//#region src/reply-dispatcher.ts
|
|
373
|
+
const DEFAULT_CHUNK_SIZE = 2e3;
|
|
374
|
+
var ReplyDispatcher = class {
|
|
375
|
+
client;
|
|
376
|
+
chunkSize;
|
|
377
|
+
constructor(options) {
|
|
378
|
+
this.client = options.client;
|
|
379
|
+
this.chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
|
|
380
|
+
}
|
|
381
|
+
async sendText(to, text) {
|
|
382
|
+
const chunks = this.chunk(text);
|
|
383
|
+
for (const chunk of chunks) try {
|
|
384
|
+
await this.client.sendText(to, chunk);
|
|
385
|
+
} catch (err) {
|
|
386
|
+
console.error(`[wechat] Failed to send text to ${to}:`, err);
|
|
387
|
+
throw err;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
async sendImage(to, imagePath, caption) {
|
|
391
|
+
try {
|
|
392
|
+
await this.client.sendImage(to, imagePath, caption);
|
|
393
|
+
} catch (err) {
|
|
394
|
+
console.error(`[wechat] Failed to send image to ${to}:`, err);
|
|
395
|
+
throw err;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
chunk(text) {
|
|
399
|
+
if (text.length <= this.chunkSize) return [text];
|
|
400
|
+
const chunks = [];
|
|
401
|
+
let remaining = text;
|
|
402
|
+
while (remaining.length > 0) {
|
|
403
|
+
if (remaining.length <= this.chunkSize) {
|
|
404
|
+
chunks.push(remaining);
|
|
405
|
+
break;
|
|
406
|
+
}
|
|
407
|
+
let breakAt = remaining.lastIndexOf("\n", this.chunkSize);
|
|
408
|
+
if (breakAt <= 0) breakAt = remaining.lastIndexOf(" ", this.chunkSize);
|
|
409
|
+
if (breakAt <= 0) breakAt = this.chunkSize;
|
|
410
|
+
chunks.push(remaining.slice(0, breakAt));
|
|
411
|
+
remaining = remaining.slice(breakAt).trimStart();
|
|
412
|
+
}
|
|
413
|
+
return chunks;
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
//#endregion
|
|
418
|
+
//#region src/utils/qrcode.ts
|
|
419
|
+
/**
|
|
420
|
+
* Display a QR code URL to the terminal.
|
|
421
|
+
* Prints the URL for the user to open in a browser.
|
|
422
|
+
* A vendored text-based QR renderer could be added here later.
|
|
423
|
+
*/
|
|
424
|
+
function displayQRUrl(url) {
|
|
425
|
+
console.log("");
|
|
426
|
+
console.log("╔══════════════════════════════════════════╗");
|
|
427
|
+
console.log("║ Scan this QR code with WeChat to login ║");
|
|
428
|
+
console.log("╠══════════════════════════════════════════╣");
|
|
429
|
+
console.log(`║ ${url}`);
|
|
430
|
+
console.log("╚══════════════════════════════════════════╝");
|
|
431
|
+
console.log("");
|
|
432
|
+
console.log("Open the URL above in your browser to see the QR code.");
|
|
433
|
+
console.log("");
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
//#endregion
|
|
437
|
+
//#region src/channel.ts
|
|
438
|
+
const HEALTH_CHECK_INTERVAL_MS = 6e4;
|
|
439
|
+
const LOGIN_POLL_INTERVAL_MS = 5e3;
|
|
440
|
+
const LOGIN_TIMEOUT_MS = 5 * 6e4;
|
|
441
|
+
var WechatChannel = class {
|
|
442
|
+
config;
|
|
443
|
+
onMessage;
|
|
444
|
+
accounts = /* @__PURE__ */ new Map();
|
|
445
|
+
callbackServers = [];
|
|
446
|
+
loginPromises = /* @__PURE__ */ new Map();
|
|
447
|
+
healthTimer = null;
|
|
448
|
+
abortController = null;
|
|
449
|
+
constructor(options) {
|
|
450
|
+
this.config = options.config;
|
|
451
|
+
this.onMessage = options.onMessage;
|
|
452
|
+
}
|
|
453
|
+
async start() {
|
|
454
|
+
this.abortController = new AbortController();
|
|
455
|
+
const resolved = this.resolveAccounts();
|
|
456
|
+
if (resolved.length === 0) {
|
|
457
|
+
console.warn("[wechat] No configured accounts found");
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
const webhookAccountsByPort = /* @__PURE__ */ new Map();
|
|
461
|
+
for (const account of resolved) {
|
|
462
|
+
const existing = webhookAccountsByPort.get(account.webhookPort) ?? [];
|
|
463
|
+
existing.push({
|
|
464
|
+
accountId: account.id,
|
|
465
|
+
apiKey: account.apiKey
|
|
466
|
+
});
|
|
467
|
+
webhookAccountsByPort.set(account.webhookPort, existing);
|
|
468
|
+
}
|
|
469
|
+
for (const [webhookPort, accounts] of webhookAccountsByPort) try {
|
|
470
|
+
this.callbackServers.push(await startCallbackServer({
|
|
471
|
+
port: webhookPort,
|
|
472
|
+
accounts,
|
|
473
|
+
onMessage: (accountId, msg) => this.routeIncoming(accountId, msg),
|
|
474
|
+
signal: this.abortController.signal
|
|
475
|
+
}));
|
|
476
|
+
} catch (err) {
|
|
477
|
+
const accountIds = accounts.map((a) => a.accountId).join(", ");
|
|
478
|
+
console.error(`[wechat] Failed to bind webhook server on port ${webhookPort} for accounts [${accountIds}]:`, err);
|
|
479
|
+
}
|
|
480
|
+
for (const account of resolved) {
|
|
481
|
+
const client = new ProxyClient(account);
|
|
482
|
+
const dispatcher = new ReplyDispatcher({ client });
|
|
483
|
+
const bot = new Bot({
|
|
484
|
+
onMessage: (msg) => this.onMessage(account.id, msg),
|
|
485
|
+
featuresGroups: this.config.features?.groups,
|
|
486
|
+
featuresImages: this.config.features?.images
|
|
487
|
+
});
|
|
488
|
+
this.accounts.set(account.id, {
|
|
489
|
+
client,
|
|
490
|
+
dispatcher,
|
|
491
|
+
bot
|
|
492
|
+
});
|
|
493
|
+
await this.ensureLoggedIn(account.id, client);
|
|
494
|
+
const webhookUrl = `http://localhost:${account.webhookPort}/webhook/wechat/${account.id}`;
|
|
495
|
+
try {
|
|
496
|
+
await client.registerWebhook(webhookUrl);
|
|
497
|
+
console.log(`[wechat] Account "${account.id}" registered webhook at ${webhookUrl}`);
|
|
498
|
+
} catch (err) {
|
|
499
|
+
console.error(`[wechat] Failed to register webhook for "${account.id}":`, err);
|
|
500
|
+
throw new Error(`Webhook registration failed for account "${account.id}": ${err instanceof Error ? err.message : String(err)}`);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
this.healthTimer = setInterval(() => this.healthCheck(), HEALTH_CHECK_INTERVAL_MS);
|
|
504
|
+
}
|
|
505
|
+
async stop() {
|
|
506
|
+
if (this.healthTimer) {
|
|
507
|
+
clearInterval(this.healthTimer);
|
|
508
|
+
this.healthTimer = null;
|
|
509
|
+
}
|
|
510
|
+
for (const [, { bot }] of this.accounts) bot.stop();
|
|
511
|
+
this.accounts.clear();
|
|
512
|
+
if (this.abortController) {
|
|
513
|
+
this.abortController.abort();
|
|
514
|
+
this.abortController = null;
|
|
515
|
+
}
|
|
516
|
+
const servers = this.callbackServers.splice(0);
|
|
517
|
+
await Promise.all(servers.map((server) => server.close().catch(() => void 0)));
|
|
518
|
+
}
|
|
519
|
+
async sendText(accountId, to, text) {
|
|
520
|
+
const entry = this.accounts.get(accountId);
|
|
521
|
+
if (!entry) throw new Error(`Unknown account: ${accountId}`);
|
|
522
|
+
try {
|
|
523
|
+
await entry.dispatcher.sendText(to, text);
|
|
524
|
+
} catch (err) {
|
|
525
|
+
if (err instanceof LoginExpiredError) {
|
|
526
|
+
await this.ensureLoggedIn(accountId, entry.client);
|
|
527
|
+
await entry.dispatcher.sendText(to, text);
|
|
528
|
+
} else throw err;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
async sendImage(accountId, to, imagePath, caption) {
|
|
532
|
+
const entry = this.accounts.get(accountId);
|
|
533
|
+
if (!entry) throw new Error(`Unknown account: ${accountId}`);
|
|
534
|
+
try {
|
|
535
|
+
await entry.dispatcher.sendImage(to, imagePath, caption);
|
|
536
|
+
} catch (err) {
|
|
537
|
+
if (err instanceof LoginExpiredError) {
|
|
538
|
+
await this.ensureLoggedIn(accountId, entry.client);
|
|
539
|
+
await entry.dispatcher.sendImage(to, imagePath, caption);
|
|
540
|
+
} else throw err;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
routeIncoming(accountId, msg) {
|
|
544
|
+
const entry = this.accounts.get(accountId);
|
|
545
|
+
if (!entry) {
|
|
546
|
+
console.warn(`[wechat] Received webhook for unknown account "${accountId}"`);
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
entry.bot.handleIncoming(msg);
|
|
550
|
+
}
|
|
551
|
+
async ensureLoggedIn(accountId, client) {
|
|
552
|
+
const existing = this.loginPromises.get(accountId);
|
|
553
|
+
if (existing) return existing;
|
|
554
|
+
const promise = this.doLogin(accountId, client).finally(() => {
|
|
555
|
+
this.loginPromises.delete(accountId);
|
|
556
|
+
});
|
|
557
|
+
this.loginPromises.set(accountId, promise);
|
|
558
|
+
return promise;
|
|
559
|
+
}
|
|
560
|
+
async doLogin(accountId, client) {
|
|
561
|
+
const status = await client.getStatus();
|
|
562
|
+
if (status.loginState === "logged_in") {
|
|
563
|
+
console.log(`[wechat] Account "${accountId}" logged in as ${status.nickName ?? status.wcId}`);
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
console.log(`[wechat] Account "${accountId}" needs login — generating QR code...`);
|
|
567
|
+
displayQRUrl(await client.getQRCode());
|
|
568
|
+
const timeoutMs = this.config.loginTimeoutMs ?? LOGIN_TIMEOUT_MS;
|
|
569
|
+
const deadline = Date.now() + timeoutMs;
|
|
570
|
+
while (Date.now() < deadline) {
|
|
571
|
+
await sleep(LOGIN_POLL_INTERVAL_MS);
|
|
572
|
+
if (this.abortController?.signal.aborted) throw new Error("Login aborted");
|
|
573
|
+
const result = await client.checkLogin();
|
|
574
|
+
if (result.status === "logged_in") {
|
|
575
|
+
console.log(`[wechat] Account "${accountId}" logged in as ${result.nickName ?? result.wcId}`);
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
if (result.status === "need_verify") console.log(`[wechat] Verification needed: ${result.verifyUrl ?? "check your phone"}`);
|
|
579
|
+
}
|
|
580
|
+
throw new Error(`[wechat] Login timed out for account "${accountId}" after ${Math.round(timeoutMs / 1e3)} seconds`);
|
|
581
|
+
}
|
|
582
|
+
async healthCheck() {
|
|
583
|
+
for (const [accountId, { client }] of this.accounts) try {
|
|
584
|
+
if ((await client.getStatus()).loginState !== "logged_in") {
|
|
585
|
+
console.warn(`[wechat] Account "${accountId}" login expired — attempting re-login`);
|
|
586
|
+
await this.ensureLoggedIn(accountId, client);
|
|
587
|
+
}
|
|
588
|
+
} catch (err) {
|
|
589
|
+
console.error(`[wechat] Health check failed for "${accountId}":`, err);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
resolveAccounts() {
|
|
593
|
+
const accounts = [];
|
|
594
|
+
const rawPort = Number(process.env.ELIZA_WECHAT_WEBHOOK_PORT);
|
|
595
|
+
const defaultPort = (Number.isFinite(rawPort) && rawPort > 0 ? rawPort : void 0) ?? this.config.webhookPort ?? 18790;
|
|
596
|
+
const defaultDevice = this.config.deviceType ?? "ipad";
|
|
597
|
+
if (this.config.accounts) for (const [id, acc] of Object.entries(this.config.accounts)) {
|
|
598
|
+
if (acc.enabled === false) continue;
|
|
599
|
+
accounts.push({
|
|
600
|
+
id,
|
|
601
|
+
apiKey: acc.apiKey,
|
|
602
|
+
proxyUrl: acc.proxyUrl,
|
|
603
|
+
deviceType: acc.deviceType ?? defaultDevice,
|
|
604
|
+
webhookPort: acc.webhookPort ?? defaultPort,
|
|
605
|
+
wcId: acc.wcId,
|
|
606
|
+
nickName: acc.nickName
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
else if (this.config.apiKey && this.config.proxyUrl) accounts.push({
|
|
610
|
+
id: "default",
|
|
611
|
+
apiKey: this.config.apiKey,
|
|
612
|
+
proxyUrl: this.config.proxyUrl,
|
|
613
|
+
deviceType: defaultDevice,
|
|
614
|
+
webhookPort: defaultPort
|
|
615
|
+
});
|
|
616
|
+
return accounts;
|
|
617
|
+
}
|
|
618
|
+
};
|
|
619
|
+
function sleep(ms) {
|
|
620
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
//#endregion
|
|
624
|
+
//#region src/runtime-bridge.ts
|
|
625
|
+
async function deliverIncomingWechatMessage(options) {
|
|
626
|
+
const runtime = options.runtime;
|
|
627
|
+
const agentId = typeof runtime.agentId === "string" && runtime.agentId.length > 0 ? runtime.agentId : stringToUuid("wechat-agent");
|
|
628
|
+
const incomingMemory = buildIncomingMemory(agentId, options.accountId, options.message);
|
|
629
|
+
const replyTarget = resolveReplyTarget(options.message);
|
|
630
|
+
let replyIndex = 0;
|
|
631
|
+
let replyDelivered = false;
|
|
632
|
+
const onResponse = async (content) => {
|
|
633
|
+
const replyText = extractReplyText(content);
|
|
634
|
+
if (!replyText) return [];
|
|
635
|
+
replyDelivered = true;
|
|
636
|
+
await options.sendText(options.accountId, replyTarget, replyText);
|
|
637
|
+
const replyMemory = buildReplyMemory(agentId, options.accountId, options.message, replyText, replyIndex);
|
|
638
|
+
replyIndex += 1;
|
|
639
|
+
await runtime.createMemory?.(replyMemory, "messages");
|
|
640
|
+
return [replyMemory];
|
|
641
|
+
};
|
|
642
|
+
await runtime.ensureConnection?.({
|
|
643
|
+
entityId: incomingMemory.entityId,
|
|
644
|
+
roomId: incomingMemory.roomId,
|
|
645
|
+
worldId: stringToUuid(`wechat:world:${options.accountId}`),
|
|
646
|
+
userName: options.message.sender,
|
|
647
|
+
userId: options.message.sender,
|
|
648
|
+
name: options.message.sender,
|
|
649
|
+
source: "wechat",
|
|
650
|
+
type: getChannelType(options.message),
|
|
651
|
+
channelId: resolveChannelId(options.message),
|
|
652
|
+
worldName: "WeChat"
|
|
653
|
+
});
|
|
654
|
+
if (typeof runtime.elizaOS?.sendMessage === "function") {
|
|
655
|
+
await maybeHandleResponseContent(await runtime.elizaOS.sendMessage(options.runtime, incomingMemory, { onResponse }), replyDelivered, onResponse);
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
if (typeof runtime.messageService?.handleMessage === "function") {
|
|
659
|
+
await maybeHandleResponseContent(await runtime.messageService.handleMessage(options.runtime, incomingMemory, onResponse), replyDelivered, onResponse);
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
if (typeof runtime.emitEvent === "function") {
|
|
663
|
+
await runtime.emitEvent(["MESSAGE_RECEIVED"], {
|
|
664
|
+
runtime: options.runtime,
|
|
665
|
+
message: incomingMemory,
|
|
666
|
+
callback: onResponse,
|
|
667
|
+
source: "wechat"
|
|
668
|
+
});
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
runtime.logger?.warn?.("[wechat] No inbound runtime message pipeline is available");
|
|
672
|
+
}
|
|
673
|
+
function buildIncomingMemory(agentId, accountId, message) {
|
|
674
|
+
return {
|
|
675
|
+
id: stringToUuid(`wechat:incoming:${accountId}:${message.id}`),
|
|
676
|
+
agentId,
|
|
677
|
+
entityId: stringToUuid(`wechat:entity:${accountId}:${message.sender}`),
|
|
678
|
+
roomId: stringToUuid(`wechat:room:${accountId}:${resolveChannelId(message)}`),
|
|
679
|
+
createdAt: message.timestamp,
|
|
680
|
+
content: {
|
|
681
|
+
text: message.content,
|
|
682
|
+
source: "wechat",
|
|
683
|
+
channelType: getChannelType(message),
|
|
684
|
+
metadata: {
|
|
685
|
+
accountId,
|
|
686
|
+
sender: message.sender,
|
|
687
|
+
recipient: message.recipient,
|
|
688
|
+
messageType: message.type,
|
|
689
|
+
threadId: message.threadId,
|
|
690
|
+
groupSubject: message.group?.subject,
|
|
691
|
+
imageUrl: message.imageUrl
|
|
692
|
+
}
|
|
693
|
+
},
|
|
694
|
+
metadata: {
|
|
695
|
+
type: "message",
|
|
696
|
+
source: "wechat",
|
|
697
|
+
provider: "wechat",
|
|
698
|
+
timestamp: message.timestamp,
|
|
699
|
+
entityName: message.sender,
|
|
700
|
+
entityUserName: message.sender,
|
|
701
|
+
fromId: message.sender,
|
|
702
|
+
sourceId: stringToUuid(`wechat:entity:${accountId}:${message.sender}`),
|
|
703
|
+
chatType: getChannelType(message),
|
|
704
|
+
messageIdFull: message.id,
|
|
705
|
+
sender: {
|
|
706
|
+
id: message.sender,
|
|
707
|
+
name: message.sender,
|
|
708
|
+
username: message.sender
|
|
709
|
+
},
|
|
710
|
+
wechat: {
|
|
711
|
+
id: message.sender,
|
|
712
|
+
userId: message.sender,
|
|
713
|
+
username: message.sender,
|
|
714
|
+
userName: message.sender,
|
|
715
|
+
name: message.sender,
|
|
716
|
+
messageId: message.id,
|
|
717
|
+
accountId,
|
|
718
|
+
recipient: message.recipient,
|
|
719
|
+
threadId: message.threadId,
|
|
720
|
+
groupSubject: message.group?.subject
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
function buildReplyMemory(agentId, accountId, message, text, replyIndex) {
|
|
726
|
+
return {
|
|
727
|
+
id: stringToUuid(`wechat:reply:${accountId}:${message.id}:${replyIndex}`),
|
|
728
|
+
agentId,
|
|
729
|
+
entityId: agentId,
|
|
730
|
+
roomId: stringToUuid(`wechat:room:${accountId}:${resolveChannelId(message)}`),
|
|
731
|
+
createdAt: Date.now(),
|
|
732
|
+
content: {
|
|
733
|
+
text,
|
|
734
|
+
source: "wechat",
|
|
735
|
+
channelType: getChannelType(message),
|
|
736
|
+
inReplyTo: message.id,
|
|
737
|
+
metadata: {
|
|
738
|
+
accountId,
|
|
739
|
+
recipient: resolveReplyTarget(message)
|
|
740
|
+
}
|
|
741
|
+
},
|
|
742
|
+
metadata: {
|
|
743
|
+
type: "message",
|
|
744
|
+
source: "wechat",
|
|
745
|
+
provider: "wechat",
|
|
746
|
+
timestamp: Date.now(),
|
|
747
|
+
fromBot: true,
|
|
748
|
+
fromId: agentId,
|
|
749
|
+
sourceId: agentId,
|
|
750
|
+
chatType: getChannelType(message),
|
|
751
|
+
messageIdFull: `wechat:reply:${message.id}:${replyIndex}`,
|
|
752
|
+
wechat: {
|
|
753
|
+
accountId,
|
|
754
|
+
recipient: resolveReplyTarget(message),
|
|
755
|
+
threadId: message.threadId
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
function getChannelType(message) {
|
|
761
|
+
return message.group ? "GROUP" : "DM";
|
|
762
|
+
}
|
|
763
|
+
function resolveChannelId(message) {
|
|
764
|
+
return message.threadId ?? message.sender;
|
|
765
|
+
}
|
|
766
|
+
function resolveReplyTarget(message) {
|
|
767
|
+
return message.threadId ?? message.sender;
|
|
768
|
+
}
|
|
769
|
+
function extractReplyText(content) {
|
|
770
|
+
if (typeof content.text !== "string") return null;
|
|
771
|
+
const trimmed = content.text.trim();
|
|
772
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
773
|
+
}
|
|
774
|
+
async function maybeHandleResponseContent(result, replyDelivered, onResponse) {
|
|
775
|
+
if (replyDelivered || !result?.responseContent) return;
|
|
776
|
+
await onResponse(result.responseContent);
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
//#endregion
|
|
780
|
+
//#region src/index.ts
|
|
781
|
+
const WECHAT_PLUGIN_PACKAGE = "@elizaos/plugin-wechat";
|
|
782
|
+
function isWechatConnectorConfigured(config) {
|
|
783
|
+
if (!config || config.enabled === false) return false;
|
|
784
|
+
if (config.apiKey) return true;
|
|
785
|
+
const accounts = config.accounts;
|
|
786
|
+
if (accounts && typeof accounts === "object") return Object.values(accounts).some((account) => {
|
|
787
|
+
if (account.enabled === false) return false;
|
|
788
|
+
return Boolean(account.apiKey);
|
|
789
|
+
});
|
|
790
|
+
return false;
|
|
791
|
+
}
|
|
792
|
+
let channel = null;
|
|
793
|
+
const wechatPlugin = {
|
|
794
|
+
name: "wechat",
|
|
795
|
+
description: "WeChat messaging via proxy API",
|
|
796
|
+
async init(config, runtime) {
|
|
797
|
+
const wechatConfig = config?.connectors?.wechat;
|
|
798
|
+
if (!wechatConfig) {
|
|
799
|
+
console.warn("[wechat] No wechat config found in connectors — skipping");
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
if (wechatConfig.enabled === false) {
|
|
803
|
+
console.log("[wechat] Plugin disabled via config");
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
channel = new WechatChannel({
|
|
807
|
+
config: wechatConfig,
|
|
808
|
+
onMessage: async (accountId, msg) => {
|
|
809
|
+
await deliverIncomingWechatMessage({
|
|
810
|
+
runtime,
|
|
811
|
+
accountId,
|
|
812
|
+
message: msg,
|
|
813
|
+
sendText: async (replyAccountId, to, text) => {
|
|
814
|
+
if (!channel) throw new Error("[wechat] Channel is not available for replies");
|
|
815
|
+
await channel.sendText(replyAccountId, to, text);
|
|
816
|
+
}
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
});
|
|
820
|
+
await channel.start();
|
|
821
|
+
console.log("[wechat] Plugin initialized");
|
|
822
|
+
return async () => {
|
|
823
|
+
if (channel) {
|
|
824
|
+
await channel.stop();
|
|
825
|
+
channel = null;
|
|
826
|
+
console.log("[wechat] Plugin stopped");
|
|
827
|
+
}
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
};
|
|
831
|
+
|
|
832
|
+
//#endregion
|
|
833
|
+
export { Bot, ProxyClient, ReplyDispatcher, WECHAT_PLUGIN_PACKAGE, WechatChannel, wechatPlugin as default, wechatPlugin, deliverIncomingWechatMessage, isWechatConnectorConfigured };
|