@elizaos/plugin-wechat 2.0.0-alpha.537 → 2.0.3-beta.5

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.
@@ -1,35 +0,0 @@
1
- import { AccountStatus, ResolvedWechatAccount } from "./types.js";
2
-
3
- //#region src/proxy-client.d.ts
4
- declare class ProxyClient {
5
- private readonly apiKey;
6
- private readonly baseUrl;
7
- private readonly accountId;
8
- private readonly deviceType;
9
- constructor(account: ResolvedWechatAccount);
10
- private request;
11
- getStatus(): Promise<AccountStatus>;
12
- getQRCode(): Promise<string>;
13
- checkLogin(): Promise<{
14
- status: "waiting" | "need_verify" | "logged_in";
15
- verifyUrl?: string;
16
- wcId?: string;
17
- nickName?: string;
18
- }>;
19
- sendText(to: string, text: string): Promise<void>;
20
- sendImage(to: string, imagePath: string, text?: string): Promise<void>;
21
- getContacts(): Promise<{
22
- friends: Array<{
23
- wxid: string;
24
- name: string;
25
- }>;
26
- chatrooms: Array<{
27
- wxid: string;
28
- name: string;
29
- }>;
30
- }>;
31
- registerWebhook(url: string): Promise<void>;
32
- get needsLogin(): boolean;
33
- }
34
- //#endregion
35
- export { ProxyClient };
@@ -1,117 +0,0 @@
1
- //#region src/proxy-client.ts
2
- const SUCCESS = 1e3;
3
- const LOGIN_NEEDED = 1001;
4
- const REQUEST_TIMEOUT_MS = 3e4;
5
- var ProxyClient = class {
6
- apiKey;
7
- baseUrl;
8
- accountId;
9
- deviceType;
10
- constructor(account) {
11
- this.apiKey = account.apiKey;
12
- this.baseUrl = normalizeProxyUrl(account.proxyUrl);
13
- this.accountId = account.id;
14
- this.deviceType = account.deviceType ?? "ipad";
15
- }
16
- async request(path, body) {
17
- const url = `${this.baseUrl}${path}`;
18
- const headers = {
19
- "Content-Type": "application/json",
20
- "X-API-Key": this.apiKey,
21
- "X-Account-ID": this.accountId,
22
- "X-Device-Type": this.deviceType
23
- };
24
- let lastError;
25
- for (let attempt = 0; attempt < 3; attempt++) try {
26
- const res = await fetch(url, {
27
- method: "POST",
28
- headers,
29
- body: body ? JSON.stringify(body) : void 0,
30
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
31
- });
32
- if (res.status === 429) {
33
- const retryAfter = res.headers.get("Retry-After");
34
- const delay = retryAfter ? Number.parseInt(retryAfter, 10) * 1e3 : Math.min(1e3 * 2 ** attempt, 8e3);
35
- await res.text().catch(() => {});
36
- await sleep(delay);
37
- continue;
38
- }
39
- return await res.json();
40
- } catch (err) {
41
- lastError = err instanceof Error ? err : new Error(String(err));
42
- await sleep(Math.min(1e3 * 2 ** attempt, 8e3));
43
- }
44
- throw lastError ?? /* @__PURE__ */ new Error(`Request failed after 3 attempts: ${path}`);
45
- }
46
- async getStatus() {
47
- const res = await this.request("/api/status");
48
- if (res.code === LOGIN_NEEDED) return {
49
- valid: true,
50
- loginState: "waiting"
51
- };
52
- if (res.code !== SUCCESS && res.code !== 1002) throw new Error(`getStatus failed: ${res.message ?? res.code}`);
53
- return requireData(res, "getStatus");
54
- }
55
- async getQRCode() {
56
- const res = await this.request("/api/qrcode");
57
- if (res.code !== SUCCESS) throw new Error(`getQRCode failed: ${res.message ?? res.code}`);
58
- return requireData(res, "getQRCode").qrCodeUrl;
59
- }
60
- async checkLogin() {
61
- const res = await this.request("/api/check-login");
62
- if (res.code !== SUCCESS && res.code !== 1002) throw new Error(`checkLogin failed: ${res.message ?? res.code}`);
63
- return requireData(res, "checkLogin");
64
- }
65
- async sendText(to, text) {
66
- const res = await this.request("/api/send-text", {
67
- to,
68
- text
69
- });
70
- if (res.code === LOGIN_NEEDED) throw new LoginExpiredError();
71
- if (res.code !== SUCCESS && res.code !== 1002) throw new Error(`sendText failed: ${res.message ?? res.code}`);
72
- }
73
- async sendImage(to, imagePath, text) {
74
- const res = await this.request("/api/send-image", {
75
- to,
76
- imagePath,
77
- text
78
- });
79
- if (res.code === LOGIN_NEEDED) throw new LoginExpiredError();
80
- if (res.code !== SUCCESS && res.code !== 1002) throw new Error(`sendImage failed: ${res.message ?? res.code}`);
81
- }
82
- async getContacts() {
83
- const res = await this.request("/api/contacts");
84
- if (res.code !== SUCCESS) throw new Error(`getContacts failed: ${res.message ?? res.code}`);
85
- return requireData(res, "getContacts");
86
- }
87
- async registerWebhook(url) {
88
- const res = await this.request("/api/webhook/register", { webhookUrl: url });
89
- if (res.code !== SUCCESS && res.code !== 1002) throw new Error(`registerWebhook failed: ${res.message ?? res.code}`);
90
- }
91
- get needsLogin() {
92
- return false;
93
- }
94
- };
95
- var LoginExpiredError = class extends Error {
96
- constructor() {
97
- super("WeChat login expired — re-login required");
98
- this.name = "LoginExpiredError";
99
- }
100
- };
101
- function sleep(ms) {
102
- return new Promise((resolve) => setTimeout(resolve, ms));
103
- }
104
- function normalizeProxyUrl(proxyUrl) {
105
- const parsed = new URL(proxyUrl);
106
- if (parsed.protocol !== "https:") throw new Error("[wechat] proxyUrl must use https://");
107
- if (parsed.username || parsed.password) throw new Error("[wechat] proxyUrl must not include credentials");
108
- parsed.hash = "";
109
- return parsed.toString().replace(/\/$/, "");
110
- }
111
- function requireData(response, action) {
112
- if (response.data === void 0) throw new Error(`${action} failed: missing response data`);
113
- return response.data;
114
- }
115
-
116
- //#endregion
117
- export { LoginExpiredError, ProxyClient };
@@ -1,17 +0,0 @@
1
- import { ProxyClient } from "./proxy-client.js";
2
-
3
- //#region src/reply-dispatcher.d.ts
4
- interface ReplyDispatcherOptions {
5
- client: ProxyClient;
6
- chunkSize?: number;
7
- }
8
- declare class ReplyDispatcher {
9
- private readonly client;
10
- private readonly chunkSize;
11
- constructor(options: ReplyDispatcherOptions);
12
- sendText(to: string, text: string): Promise<void>;
13
- sendImage(to: string, imagePath: string, caption?: string): Promise<void>;
14
- private chunk;
15
- }
16
- //#endregion
17
- export { ReplyDispatcher };
@@ -1,47 +0,0 @@
1
- //#region src/reply-dispatcher.ts
2
- const DEFAULT_CHUNK_SIZE = 2e3;
3
- var ReplyDispatcher = class {
4
- client;
5
- chunkSize;
6
- constructor(options) {
7
- this.client = options.client;
8
- this.chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
9
- }
10
- async sendText(to, text) {
11
- const chunks = this.chunk(text);
12
- for (const chunk of chunks) try {
13
- await this.client.sendText(to, chunk);
14
- } catch (err) {
15
- console.error(`[wechat] Failed to send text to ${to}:`, err);
16
- throw err;
17
- }
18
- }
19
- async sendImage(to, imagePath, caption) {
20
- try {
21
- await this.client.sendImage(to, imagePath, caption);
22
- } catch (err) {
23
- console.error(`[wechat] Failed to send image to ${to}:`, err);
24
- throw err;
25
- }
26
- }
27
- chunk(text) {
28
- if (text.length <= this.chunkSize) return [text];
29
- const chunks = [];
30
- let remaining = text;
31
- while (remaining.length > 0) {
32
- if (remaining.length <= this.chunkSize) {
33
- chunks.push(remaining);
34
- break;
35
- }
36
- let breakAt = remaining.lastIndexOf("\n", this.chunkSize);
37
- if (breakAt <= 0) breakAt = remaining.lastIndexOf(" ", this.chunkSize);
38
- if (breakAt <= 0) breakAt = this.chunkSize;
39
- chunks.push(remaining.slice(0, breakAt));
40
- remaining = remaining.slice(breakAt).trimStart();
41
- }
42
- return chunks;
43
- }
44
- };
45
-
46
- //#endregion
47
- export { ReplyDispatcher };
@@ -1,12 +0,0 @@
1
- import { WechatMessageContext } from "./types.js";
2
-
3
- //#region src/runtime-bridge.d.ts
4
- interface IncomingWechatDeliveryOptions {
5
- runtime: unknown;
6
- accountId: string;
7
- message: WechatMessageContext;
8
- sendText: (accountId: string, to: string, text: string) => Promise<void>;
9
- }
10
- declare function deliverIncomingWechatMessage(options: IncomingWechatDeliveryOptions): Promise<void>;
11
- //#endregion
12
- export { deliverIncomingWechatMessage };
@@ -1,159 +0,0 @@
1
- import { stringToUuid } from "@elizaos/core";
2
-
3
- //#region src/runtime-bridge.ts
4
- async function deliverIncomingWechatMessage(options) {
5
- const runtime = options.runtime;
6
- const agentId = typeof runtime.agentId === "string" && runtime.agentId.length > 0 ? runtime.agentId : stringToUuid("wechat-agent");
7
- const incomingMemory = buildIncomingMemory(agentId, options.accountId, options.message);
8
- const replyTarget = resolveReplyTarget(options.message);
9
- let replyIndex = 0;
10
- let replyDelivered = false;
11
- const onResponse = async (content) => {
12
- const replyText = extractReplyText(content);
13
- if (!replyText) return [];
14
- replyDelivered = true;
15
- await options.sendText(options.accountId, replyTarget, replyText);
16
- const replyMemory = buildReplyMemory(agentId, options.accountId, options.message, replyText, replyIndex);
17
- replyIndex += 1;
18
- await runtime.createMemory?.(replyMemory, "messages");
19
- return [replyMemory];
20
- };
21
- await runtime.ensureConnection?.({
22
- entityId: incomingMemory.entityId,
23
- roomId: incomingMemory.roomId,
24
- worldId: stringToUuid(`wechat:world:${options.accountId}`),
25
- userName: options.message.sender,
26
- userId: options.message.sender,
27
- name: options.message.sender,
28
- source: "wechat",
29
- type: getChannelType(options.message),
30
- channelId: resolveChannelId(options.message),
31
- worldName: "WeChat"
32
- });
33
- if (typeof runtime.elizaOS?.sendMessage === "function") {
34
- await maybeHandleResponseContent(await runtime.elizaOS.sendMessage(options.runtime, incomingMemory, { onResponse }), replyDelivered, onResponse);
35
- return;
36
- }
37
- if (typeof runtime.messageService?.handleMessage === "function") {
38
- await maybeHandleResponseContent(await runtime.messageService.handleMessage(options.runtime, incomingMemory, onResponse), replyDelivered, onResponse);
39
- return;
40
- }
41
- if (typeof runtime.emitEvent === "function") {
42
- await runtime.emitEvent(["MESSAGE_RECEIVED"], {
43
- runtime: options.runtime,
44
- message: incomingMemory,
45
- callback: onResponse,
46
- source: "wechat"
47
- });
48
- return;
49
- }
50
- runtime.logger?.warn?.("[wechat] No inbound runtime message pipeline is available");
51
- }
52
- function buildIncomingMemory(agentId, accountId, message) {
53
- return {
54
- id: stringToUuid(`wechat:incoming:${accountId}:${message.id}`),
55
- agentId,
56
- entityId: stringToUuid(`wechat:entity:${accountId}:${message.sender}`),
57
- roomId: stringToUuid(`wechat:room:${accountId}:${resolveChannelId(message)}`),
58
- createdAt: message.timestamp,
59
- content: {
60
- text: message.content,
61
- source: "wechat",
62
- channelType: getChannelType(message),
63
- metadata: {
64
- accountId,
65
- sender: message.sender,
66
- recipient: message.recipient,
67
- messageType: message.type,
68
- threadId: message.threadId,
69
- groupSubject: message.group?.subject,
70
- imageUrl: message.imageUrl
71
- }
72
- },
73
- metadata: {
74
- type: "message",
75
- source: "wechat",
76
- provider: "wechat",
77
- timestamp: message.timestamp,
78
- entityName: message.sender,
79
- entityUserName: message.sender,
80
- fromId: message.sender,
81
- sourceId: stringToUuid(`wechat:entity:${accountId}:${message.sender}`),
82
- chatType: getChannelType(message),
83
- messageIdFull: message.id,
84
- sender: {
85
- id: message.sender,
86
- name: message.sender,
87
- username: message.sender
88
- },
89
- wechat: {
90
- id: message.sender,
91
- userId: message.sender,
92
- username: message.sender,
93
- userName: message.sender,
94
- name: message.sender,
95
- messageId: message.id,
96
- accountId,
97
- recipient: message.recipient,
98
- threadId: message.threadId,
99
- groupSubject: message.group?.subject
100
- }
101
- }
102
- };
103
- }
104
- function buildReplyMemory(agentId, accountId, message, text, replyIndex) {
105
- return {
106
- id: stringToUuid(`wechat:reply:${accountId}:${message.id}:${replyIndex}`),
107
- agentId,
108
- entityId: agentId,
109
- roomId: stringToUuid(`wechat:room:${accountId}:${resolveChannelId(message)}`),
110
- createdAt: Date.now(),
111
- content: {
112
- text,
113
- source: "wechat",
114
- channelType: getChannelType(message),
115
- inReplyTo: message.id,
116
- metadata: {
117
- accountId,
118
- recipient: resolveReplyTarget(message)
119
- }
120
- },
121
- metadata: {
122
- type: "message",
123
- source: "wechat",
124
- provider: "wechat",
125
- timestamp: Date.now(),
126
- fromBot: true,
127
- fromId: agentId,
128
- sourceId: agentId,
129
- chatType: getChannelType(message),
130
- messageIdFull: `wechat:reply:${message.id}:${replyIndex}`,
131
- wechat: {
132
- accountId,
133
- recipient: resolveReplyTarget(message),
134
- threadId: message.threadId
135
- }
136
- }
137
- };
138
- }
139
- function getChannelType(message) {
140
- return message.group ? "GROUP" : "DM";
141
- }
142
- function resolveChannelId(message) {
143
- return message.threadId ?? message.sender;
144
- }
145
- function resolveReplyTarget(message) {
146
- return message.threadId ?? message.sender;
147
- }
148
- function extractReplyText(content) {
149
- if (typeof content.text !== "string") return null;
150
- const trimmed = content.text.trim();
151
- return trimmed.length > 0 ? trimmed : null;
152
- }
153
- async function maybeHandleResponseContent(result, replyDelivered, onResponse) {
154
- if (replyDelivered || !result?.responseContent) return;
155
- await onResponse(result.responseContent);
156
- }
157
-
158
- //#endregion
159
- export { deliverIncomingWechatMessage };
package/dist/types.d.ts DELETED
@@ -1,61 +0,0 @@
1
- //#region src/types.d.ts
2
- type DeviceType = "ipad" | "mac";
3
- type LoginStatus = "waiting" | "need_verify" | "logged_in";
4
- interface WechatAccountConfig {
5
- enabled?: boolean;
6
- name?: string;
7
- apiKey: string;
8
- proxyUrl: string;
9
- deviceType?: DeviceType;
10
- webhookPort?: number;
11
- webhookUrl?: string;
12
- wcId?: string;
13
- nickName?: string;
14
- }
15
- interface WechatConfig {
16
- enabled?: boolean;
17
- apiKey?: string;
18
- proxyUrl?: string;
19
- webhookPort?: number;
20
- deviceType?: DeviceType;
21
- loginTimeoutMs?: number;
22
- accounts?: Record<string, WechatAccountConfig>;
23
- features?: {
24
- images?: boolean;
25
- groups?: boolean;
26
- };
27
- }
28
- interface ResolvedWechatAccount {
29
- id: string;
30
- apiKey: string;
31
- proxyUrl: string;
32
- deviceType: DeviceType;
33
- webhookPort: number;
34
- wcId?: string;
35
- nickName?: string;
36
- }
37
- type WechatMessageType = "text" | "image" | "video" | "file" | "voice" | "unknown";
38
- interface WechatMessageContext {
39
- id: string;
40
- type: WechatMessageType;
41
- sender: string;
42
- recipient: string;
43
- content: string;
44
- timestamp: number;
45
- threadId?: string;
46
- group?: {
47
- subject: string;
48
- };
49
- imageUrl?: string;
50
- raw: unknown;
51
- }
52
- interface AccountStatus {
53
- valid: boolean;
54
- wcId?: string;
55
- loginState: LoginStatus;
56
- nickName?: string;
57
- tier?: string;
58
- quota?: number;
59
- }
60
- //#endregion
61
- export { AccountStatus, ResolvedWechatAccount, WechatConfig, WechatMessageContext };
@@ -1,20 +0,0 @@
1
- //#region src/utils/qrcode.ts
2
- /**
3
- * Display a QR code URL to the terminal.
4
- * Prints the URL for the user to open in a browser.
5
- * A vendored text-based QR renderer could be added here later.
6
- */
7
- function displayQRUrl(url) {
8
- console.log("");
9
- console.log("╔══════════════════════════════════════════╗");
10
- console.log("║ Scan this QR code with WeChat to login ║");
11
- console.log("╠══════════════════════════════════════════╣");
12
- console.log(`║ ${url}`);
13
- console.log("╚══════════════════════════════════════════╝");
14
- console.log("");
15
- console.log("Open the URL above in your browser to see the QR code.");
16
- console.log("");
17
- }
18
-
19
- //#endregion
20
- export { displayQRUrl };
@@ -1,190 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from "vitest";
2
- import { startCallbackServer } from "./callback-server";
3
-
4
- const servers: Array<{ close: () => Promise<void> }> = [];
5
-
6
- afterEach(async () => {
7
- await Promise.all(servers.splice(0).map((server) => server.close()));
8
- });
9
-
10
- describe("startCallbackServer", () => {
11
- it("routes a webhook to the matching account and validates that account's API key", async () => {
12
- const onMessage = vi.fn();
13
- const server = await startCallbackServer({
14
- port: 0,
15
- accounts: [
16
- { accountId: "main", apiKey: "main-key" },
17
- { accountId: "secondary", apiKey: "secondary-key" },
18
- ],
19
- onMessage,
20
- });
21
- servers.push(server);
22
-
23
- const response = await fetch(
24
- `http://127.0.0.1:${server.port}/webhook/wechat/secondary`,
25
- {
26
- method: "POST",
27
- headers: {
28
- "content-type": "application/json",
29
- "x-api-key": "secondary-key",
30
- },
31
- body: JSON.stringify({
32
- type: 60001,
33
- sender: "wxid-alice",
34
- recipient: "wxid-agent",
35
- content: "hello",
36
- timestamp: 123,
37
- }),
38
- },
39
- );
40
-
41
- expect(response.status).toBe(200);
42
- expect(onMessage).toHaveBeenCalledWith(
43
- "secondary",
44
- expect.objectContaining({
45
- sender: "wxid-alice",
46
- content: "hello",
47
- }),
48
- );
49
- });
50
-
51
- it("rejects requests signed with another account's API key", async () => {
52
- const onMessage = vi.fn();
53
- const server = await startCallbackServer({
54
- port: 0,
55
- accounts: [
56
- { accountId: "main", apiKey: "main-key" },
57
- { accountId: "secondary", apiKey: "secondary-key" },
58
- ],
59
- onMessage,
60
- });
61
- servers.push(server);
62
-
63
- const response = await fetch(
64
- `http://127.0.0.1:${server.port}/webhook/wechat/secondary`,
65
- {
66
- method: "POST",
67
- headers: {
68
- "content-type": "application/json",
69
- "x-api-key": "main-key",
70
- },
71
- body: JSON.stringify({
72
- type: 60001,
73
- sender: "wxid-alice",
74
- recipient: "wxid-agent",
75
- content: "hello",
76
- timestamp: 123,
77
- }),
78
- },
79
- );
80
-
81
- expect(response.status).toBe(401);
82
- expect(onMessage).not.toHaveBeenCalled();
83
- });
84
-
85
- it("rejects oversized webhook payloads", async () => {
86
- const onMessage = vi.fn();
87
- const server = await startCallbackServer({
88
- port: 0,
89
- accounts: [{ accountId: "main", apiKey: "main-key" }],
90
- maxBodyBytes: 64,
91
- onMessage,
92
- });
93
- servers.push(server);
94
-
95
- const response = await fetch(
96
- `http://127.0.0.1:${server.port}/webhook/wechat/main`,
97
- {
98
- method: "POST",
99
- headers: {
100
- "content-type": "application/json",
101
- "x-api-key": "main-key",
102
- },
103
- body: JSON.stringify({
104
- type: 60001,
105
- sender: "wxid-alice",
106
- recipient: "wxid-agent",
107
- content: "x".repeat(512),
108
- timestamp: 123,
109
- }),
110
- },
111
- );
112
-
113
- expect(response.status).toBe(413);
114
- expect(onMessage).not.toHaveBeenCalled();
115
- });
116
-
117
- it("maps voice message type correctly", async () => {
118
- const onMessage = vi.fn();
119
- const server = await startCallbackServer({
120
- port: 0,
121
- accounts: [{ accountId: "main", apiKey: "key" }],
122
- onMessage,
123
- });
124
- servers.push(server);
125
-
126
- const response = await fetch(
127
- `http://127.0.0.1:${server.port}/webhook/wechat/main`,
128
- {
129
- method: "POST",
130
- headers: { "content-type": "application/json", "x-api-key": "key" },
131
- body: JSON.stringify({
132
- data: {
133
- type: 60003,
134
- sender: "wxid-alice",
135
- recipient: "wxid-agent",
136
- content: "",
137
- timestamp: 456,
138
- mediaUrl: "https://example.com/voice.amr",
139
- },
140
- }),
141
- },
142
- );
143
-
144
- expect(response.status).toBe(200);
145
- expect(onMessage).toHaveBeenCalledWith(
146
- "main",
147
- expect.objectContaining({
148
- type: "voice",
149
- imageUrl: "https://example.com/voice.amr",
150
- }),
151
- );
152
- });
153
-
154
- it("maps group video message type correctly", async () => {
155
- const onMessage = vi.fn();
156
- const server = await startCallbackServer({
157
- port: 0,
158
- accounts: [{ accountId: "main", apiKey: "key" }],
159
- onMessage,
160
- });
161
- servers.push(server);
162
-
163
- const response = await fetch(
164
- `http://127.0.0.1:${server.port}/webhook/wechat/main`,
165
- {
166
- method: "POST",
167
- headers: { "content-type": "application/json", "x-api-key": "key" },
168
- body: JSON.stringify({
169
- data: {
170
- type: 80004,
171
- sender: "room@chatroom",
172
- recipient: "wxid-agent",
173
- content: "",
174
- timestamp: 789,
175
- mediaUrl: "https://example.com/video.mp4",
176
- },
177
- }),
178
- },
179
- );
180
-
181
- expect(response.status).toBe(200);
182
- expect(onMessage).toHaveBeenCalledWith(
183
- "main",
184
- expect.objectContaining({
185
- type: "video",
186
- imageUrl: "https://example.com/video.mp4",
187
- }),
188
- );
189
- });
190
- });