@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.
package/dist/channel.js DELETED
@@ -1,194 +0,0 @@
1
- import { Bot } from "./bot.js";
2
- import { startCallbackServer } from "./callback-server.js";
3
- import { LoginExpiredError, ProxyClient } from "./proxy-client.js";
4
- import { ReplyDispatcher } from "./reply-dispatcher.js";
5
- import { displayQRUrl } from "./utils/qrcode.js";
6
-
7
- //#region src/channel.ts
8
- const HEALTH_CHECK_INTERVAL_MS = 6e4;
9
- const LOGIN_POLL_INTERVAL_MS = 5e3;
10
- const LOGIN_TIMEOUT_MS = 5 * 6e4;
11
- var WechatChannel = class {
12
- config;
13
- onMessage;
14
- accounts = /* @__PURE__ */ new Map();
15
- callbackServers = [];
16
- loginPromises = /* @__PURE__ */ new Map();
17
- healthTimer = null;
18
- abortController = null;
19
- constructor(options) {
20
- this.config = options.config;
21
- this.onMessage = options.onMessage;
22
- }
23
- async start() {
24
- this.abortController = new AbortController();
25
- const resolved = this.resolveAccounts();
26
- if (resolved.length === 0) {
27
- console.warn("[wechat] No configured accounts found");
28
- return;
29
- }
30
- const webhookAccountsByPort = /* @__PURE__ */ new Map();
31
- for (const account of resolved) {
32
- const existing = webhookAccountsByPort.get(account.webhookPort) ?? [];
33
- existing.push({
34
- accountId: account.id,
35
- apiKey: account.apiKey
36
- });
37
- webhookAccountsByPort.set(account.webhookPort, existing);
38
- }
39
- for (const [webhookPort, accounts] of webhookAccountsByPort) try {
40
- this.callbackServers.push(await startCallbackServer({
41
- port: webhookPort,
42
- accounts,
43
- onMessage: (accountId, msg) => this.routeIncoming(accountId, msg),
44
- signal: this.abortController.signal
45
- }));
46
- } catch (err) {
47
- const accountIds = accounts.map((a) => a.accountId).join(", ");
48
- console.error(`[wechat] Failed to bind webhook server on port ${webhookPort} for accounts [${accountIds}]:`, err);
49
- }
50
- for (const account of resolved) {
51
- const client = new ProxyClient(account);
52
- const dispatcher = new ReplyDispatcher({ client });
53
- const bot = new Bot({
54
- onMessage: (msg) => this.onMessage(account.id, msg),
55
- featuresGroups: this.config.features?.groups,
56
- featuresImages: this.config.features?.images
57
- });
58
- this.accounts.set(account.id, {
59
- client,
60
- dispatcher,
61
- bot
62
- });
63
- await this.ensureLoggedIn(account.id, client);
64
- const webhookUrl = `http://localhost:${account.webhookPort}/webhook/wechat/${account.id}`;
65
- try {
66
- await client.registerWebhook(webhookUrl);
67
- console.log(`[wechat] Account "${account.id}" registered webhook at ${webhookUrl}`);
68
- } catch (err) {
69
- console.error(`[wechat] Failed to register webhook for "${account.id}":`, err);
70
- throw new Error(`Webhook registration failed for account "${account.id}": ${err instanceof Error ? err.message : String(err)}`);
71
- }
72
- }
73
- this.healthTimer = setInterval(() => this.healthCheck(), HEALTH_CHECK_INTERVAL_MS);
74
- }
75
- async stop() {
76
- if (this.healthTimer) {
77
- clearInterval(this.healthTimer);
78
- this.healthTimer = null;
79
- }
80
- for (const [, { bot }] of this.accounts) bot.stop();
81
- this.accounts.clear();
82
- if (this.abortController) {
83
- this.abortController.abort();
84
- this.abortController = null;
85
- }
86
- const servers = this.callbackServers.splice(0);
87
- await Promise.all(servers.map((server) => server.close().catch(() => void 0)));
88
- }
89
- async sendText(accountId, to, text) {
90
- const entry = this.accounts.get(accountId);
91
- if (!entry) throw new Error(`Unknown account: ${accountId}`);
92
- try {
93
- await entry.dispatcher.sendText(to, text);
94
- } catch (err) {
95
- if (err instanceof LoginExpiredError) {
96
- await this.ensureLoggedIn(accountId, entry.client);
97
- await entry.dispatcher.sendText(to, text);
98
- } else throw err;
99
- }
100
- }
101
- async sendImage(accountId, to, imagePath, caption) {
102
- const entry = this.accounts.get(accountId);
103
- if (!entry) throw new Error(`Unknown account: ${accountId}`);
104
- try {
105
- await entry.dispatcher.sendImage(to, imagePath, caption);
106
- } catch (err) {
107
- if (err instanceof LoginExpiredError) {
108
- await this.ensureLoggedIn(accountId, entry.client);
109
- await entry.dispatcher.sendImage(to, imagePath, caption);
110
- } else throw err;
111
- }
112
- }
113
- routeIncoming(accountId, msg) {
114
- const entry = this.accounts.get(accountId);
115
- if (!entry) {
116
- console.warn(`[wechat] Received webhook for unknown account "${accountId}"`);
117
- return;
118
- }
119
- entry.bot.handleIncoming(msg);
120
- }
121
- async ensureLoggedIn(accountId, client) {
122
- const existing = this.loginPromises.get(accountId);
123
- if (existing) return existing;
124
- const promise = this.doLogin(accountId, client).finally(() => {
125
- this.loginPromises.delete(accountId);
126
- });
127
- this.loginPromises.set(accountId, promise);
128
- return promise;
129
- }
130
- async doLogin(accountId, client) {
131
- const status = await client.getStatus();
132
- if (status.loginState === "logged_in") {
133
- console.log(`[wechat] Account "${accountId}" logged in as ${status.nickName ?? status.wcId}`);
134
- return;
135
- }
136
- console.log(`[wechat] Account "${accountId}" needs login — generating QR code...`);
137
- displayQRUrl(await client.getQRCode());
138
- const timeoutMs = this.config.loginTimeoutMs ?? LOGIN_TIMEOUT_MS;
139
- const deadline = Date.now() + timeoutMs;
140
- while (Date.now() < deadline) {
141
- await sleep(LOGIN_POLL_INTERVAL_MS);
142
- if (this.abortController?.signal.aborted) throw new Error("Login aborted");
143
- const result = await client.checkLogin();
144
- if (result.status === "logged_in") {
145
- console.log(`[wechat] Account "${accountId}" logged in as ${result.nickName ?? result.wcId}`);
146
- return;
147
- }
148
- if (result.status === "need_verify") console.log(`[wechat] Verification needed: ${result.verifyUrl ?? "check your phone"}`);
149
- }
150
- throw new Error(`[wechat] Login timed out for account "${accountId}" after ${Math.round(timeoutMs / 1e3)} seconds`);
151
- }
152
- async healthCheck() {
153
- for (const [accountId, { client }] of this.accounts) try {
154
- if ((await client.getStatus()).loginState !== "logged_in") {
155
- console.warn(`[wechat] Account "${accountId}" login expired — attempting re-login`);
156
- await this.ensureLoggedIn(accountId, client);
157
- }
158
- } catch (err) {
159
- console.error(`[wechat] Health check failed for "${accountId}":`, err);
160
- }
161
- }
162
- resolveAccounts() {
163
- const accounts = [];
164
- const rawPort = Number(process.env.ELIZA_WECHAT_WEBHOOK_PORT);
165
- const defaultPort = (Number.isFinite(rawPort) && rawPort > 0 ? rawPort : void 0) ?? this.config.webhookPort ?? 18790;
166
- const defaultDevice = this.config.deviceType ?? "ipad";
167
- if (this.config.accounts) for (const [id, acc] of Object.entries(this.config.accounts)) {
168
- if (acc.enabled === false) continue;
169
- accounts.push({
170
- id,
171
- apiKey: acc.apiKey,
172
- proxyUrl: acc.proxyUrl,
173
- deviceType: acc.deviceType ?? defaultDevice,
174
- webhookPort: acc.webhookPort ?? defaultPort,
175
- wcId: acc.wcId,
176
- nickName: acc.nickName
177
- });
178
- }
179
- else if (this.config.apiKey && this.config.proxyUrl) accounts.push({
180
- id: "default",
181
- apiKey: this.config.apiKey,
182
- proxyUrl: this.config.proxyUrl,
183
- deviceType: defaultDevice,
184
- webhookPort: defaultPort
185
- });
186
- return accounts;
187
- }
188
- };
189
- function sleep(ms) {
190
- return new Promise((resolve) => setTimeout(resolve, ms));
191
- }
192
-
193
- //#endregion
194
- export { WechatChannel };
package/dist/index.d.ts DELETED
@@ -1,173 +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
- //#region src/bot.d.ts
62
- interface BotOptions {
63
- onMessage: (msg: WechatMessageContext) => void | Promise<void>;
64
- featuresGroups?: boolean;
65
- featuresImages?: boolean;
66
- /** Deduplication window in milliseconds. Defaults to 30 minutes. */
67
- dedupWindowMs?: number;
68
- }
69
- declare class Bot {
70
- private readonly seen;
71
- private readonly onMessage;
72
- private readonly featuresGroups;
73
- private readonly featuresImages;
74
- private readonly dedupWindowMs;
75
- private cleanupTimer;
76
- constructor(options: BotOptions);
77
- handleIncoming(message: WechatMessageContext): void;
78
- private isDuplicate;
79
- private cleanup;
80
- stop(): void;
81
- }
82
- //#endregion
83
- //#region src/channel.d.ts
84
- interface ChannelOptions {
85
- config: WechatConfig;
86
- onMessage: (accountId: string, msg: WechatMessageContext) => void | Promise<void>;
87
- }
88
- declare class WechatChannel {
89
- private readonly config;
90
- private readonly onMessage;
91
- private readonly accounts;
92
- private readonly callbackServers;
93
- private readonly loginPromises;
94
- private healthTimer;
95
- private abortController;
96
- constructor(options: ChannelOptions);
97
- start(): Promise<void>;
98
- stop(): Promise<void>;
99
- sendText(accountId: string, to: string, text: string): Promise<void>;
100
- sendImage(accountId: string, to: string, imagePath: string, caption?: string): Promise<void>;
101
- private routeIncoming;
102
- private ensureLoggedIn;
103
- private doLogin;
104
- private healthCheck;
105
- private resolveAccounts;
106
- }
107
- //#endregion
108
- //#region src/proxy-client.d.ts
109
- declare class ProxyClient {
110
- private readonly apiKey;
111
- private readonly baseUrl;
112
- private readonly accountId;
113
- private readonly deviceType;
114
- constructor(account: ResolvedWechatAccount);
115
- private request;
116
- getStatus(): Promise<AccountStatus>;
117
- getQRCode(): Promise<string>;
118
- checkLogin(): Promise<{
119
- status: "waiting" | "need_verify" | "logged_in";
120
- verifyUrl?: string;
121
- wcId?: string;
122
- nickName?: string;
123
- }>;
124
- sendText(to: string, text: string): Promise<void>;
125
- sendImage(to: string, imagePath: string, text?: string): Promise<void>;
126
- getContacts(): Promise<{
127
- friends: Array<{
128
- wxid: string;
129
- name: string;
130
- }>;
131
- chatrooms: Array<{
132
- wxid: string;
133
- name: string;
134
- }>;
135
- }>;
136
- registerWebhook(url: string): Promise<void>;
137
- get needsLogin(): boolean;
138
- }
139
- //#endregion
140
- //#region src/reply-dispatcher.d.ts
141
- interface ReplyDispatcherOptions {
142
- client: ProxyClient;
143
- chunkSize?: number;
144
- }
145
- declare class ReplyDispatcher {
146
- private readonly client;
147
- private readonly chunkSize;
148
- constructor(options: ReplyDispatcherOptions);
149
- sendText(to: string, text: string): Promise<void>;
150
- sendImage(to: string, imagePath: string, caption?: string): Promise<void>;
151
- private chunk;
152
- }
153
- //#endregion
154
- //#region src/runtime-bridge.d.ts
155
- interface IncomingWechatDeliveryOptions {
156
- runtime: unknown;
157
- accountId: string;
158
- message: WechatMessageContext;
159
- sendText: (accountId: string, to: string, text: string) => Promise<void>;
160
- }
161
- declare function deliverIncomingWechatMessage(options: IncomingWechatDeliveryOptions): Promise<void>;
162
- //#endregion
163
- //#region src/index.d.ts
164
- declare const WECHAT_PLUGIN_PACKAGE: "@elizaos/plugin-wechat";
165
- declare function isWechatConnectorConfigured(config: WechatConfig | Record<string, unknown> | null | undefined): boolean;
166
- interface Plugin {
167
- name: string;
168
- description: string;
169
- init?: (config: Record<string, unknown>, runtime: unknown) => Promise<void | (() => Promise<void>)>;
170
- }
171
- declare const wechatPlugin: Plugin;
172
- //#endregion
173
- export { Bot, Plugin, ProxyClient, ReplyDispatcher, WECHAT_PLUGIN_PACKAGE, WechatChannel, type WechatConfig, type WechatMessageContext, wechatPlugin as default, wechatPlugin, deliverIncomingWechatMessage, isWechatConnectorConfigured };