@colin3191/feishu 0.1.2

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/src/media.ts ADDED
@@ -0,0 +1,515 @@
1
+ import type { ClawdbotConfig } from "clawdbot/plugin-sdk";
2
+ import type { FeishuConfig } from "./types.js";
3
+ import { createFeishuClient } from "./client.js";
4
+ import { resolveReceiveIdType, normalizeFeishuTarget } from "./targets.js";
5
+ import fs from "fs";
6
+ import path from "path";
7
+ import os from "os";
8
+ import { Readable } from "stream";
9
+
10
+ export type DownloadImageResult = {
11
+ buffer: Buffer;
12
+ contentType?: string;
13
+ };
14
+
15
+ export type DownloadMessageResourceResult = {
16
+ buffer: Buffer;
17
+ contentType?: string;
18
+ fileName?: string;
19
+ };
20
+
21
+ /**
22
+ * Download an image from Feishu using image_key.
23
+ * Used for downloading images sent in messages.
24
+ */
25
+ export async function downloadImageFeishu(params: {
26
+ cfg: ClawdbotConfig;
27
+ imageKey: string;
28
+ }): Promise<DownloadImageResult> {
29
+ const { cfg, imageKey } = params;
30
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
31
+ if (!feishuCfg) {
32
+ throw new Error("Feishu channel not configured");
33
+ }
34
+
35
+ const client = createFeishuClient(feishuCfg);
36
+
37
+ const response = await client.im.image.get({
38
+ path: { image_key: imageKey },
39
+ });
40
+
41
+ const responseAny = response as any;
42
+ if (responseAny.code !== undefined && responseAny.code !== 0) {
43
+ throw new Error(`Feishu image download failed: ${responseAny.msg || `code ${responseAny.code}`}`);
44
+ }
45
+
46
+ // Handle various response formats from Feishu SDK
47
+ let buffer: Buffer;
48
+
49
+ if (Buffer.isBuffer(response)) {
50
+ buffer = response;
51
+ } else if (response instanceof ArrayBuffer) {
52
+ buffer = Buffer.from(response);
53
+ } else if (responseAny.data && Buffer.isBuffer(responseAny.data)) {
54
+ buffer = responseAny.data;
55
+ } else if (responseAny.data instanceof ArrayBuffer) {
56
+ buffer = Buffer.from(responseAny.data);
57
+ } else if (typeof responseAny.getReadableStream === "function") {
58
+ // SDK provides getReadableStream method
59
+ const stream = responseAny.getReadableStream();
60
+ const chunks: Buffer[] = [];
61
+ for await (const chunk of stream) {
62
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
63
+ }
64
+ buffer = Buffer.concat(chunks);
65
+ } else if (typeof responseAny.writeFile === "function") {
66
+ // SDK provides writeFile method - use a temp file
67
+ const tmpPath = path.join(os.tmpdir(), `feishu_img_${Date.now()}_${imageKey}`);
68
+ await responseAny.writeFile(tmpPath);
69
+ buffer = await fs.promises.readFile(tmpPath);
70
+ await fs.promises.unlink(tmpPath).catch(() => {}); // cleanup
71
+ } else if (typeof responseAny[Symbol.asyncIterator] === "function") {
72
+ // Response is an async iterable
73
+ const chunks: Buffer[] = [];
74
+ for await (const chunk of responseAny) {
75
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
76
+ }
77
+ buffer = Buffer.concat(chunks);
78
+ } else if (typeof responseAny.read === "function") {
79
+ // Response is a Readable stream
80
+ const chunks: Buffer[] = [];
81
+ for await (const chunk of responseAny as Readable) {
82
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
83
+ }
84
+ buffer = Buffer.concat(chunks);
85
+ } else {
86
+ // Debug: log what we actually received
87
+ const keys = Object.keys(responseAny);
88
+ const types = keys.map(k => `${k}: ${typeof responseAny[k]}`).join(", ");
89
+ throw new Error(
90
+ `Feishu image download failed: unexpected response format. Keys: [${types}]`,
91
+ );
92
+ }
93
+
94
+ return { buffer };
95
+ }
96
+
97
+ /**
98
+ * Download a message resource (file/image/audio/video) from Feishu.
99
+ * Used for downloading files, audio, and video from messages.
100
+ */
101
+ export async function downloadMessageResourceFeishu(params: {
102
+ cfg: ClawdbotConfig;
103
+ messageId: string;
104
+ fileKey: string;
105
+ type: "image" | "file";
106
+ }): Promise<DownloadMessageResourceResult> {
107
+ const { cfg, messageId, fileKey, type } = params;
108
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
109
+ if (!feishuCfg) {
110
+ throw new Error("Feishu channel not configured");
111
+ }
112
+
113
+ const client = createFeishuClient(feishuCfg);
114
+
115
+ const response = await client.im.messageResource.get({
116
+ path: { message_id: messageId, file_key: fileKey },
117
+ params: { type },
118
+ });
119
+
120
+ const responseAny = response as any;
121
+ if (responseAny.code !== undefined && responseAny.code !== 0) {
122
+ throw new Error(
123
+ `Feishu message resource download failed: ${responseAny.msg || `code ${responseAny.code}`}`,
124
+ );
125
+ }
126
+
127
+ // Handle various response formats from Feishu SDK
128
+ let buffer: Buffer;
129
+
130
+ if (Buffer.isBuffer(response)) {
131
+ buffer = response;
132
+ } else if (response instanceof ArrayBuffer) {
133
+ buffer = Buffer.from(response);
134
+ } else if (responseAny.data && Buffer.isBuffer(responseAny.data)) {
135
+ buffer = responseAny.data;
136
+ } else if (responseAny.data instanceof ArrayBuffer) {
137
+ buffer = Buffer.from(responseAny.data);
138
+ } else if (typeof responseAny.getReadableStream === "function") {
139
+ // SDK provides getReadableStream method
140
+ const stream = responseAny.getReadableStream();
141
+ const chunks: Buffer[] = [];
142
+ for await (const chunk of stream) {
143
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
144
+ }
145
+ buffer = Buffer.concat(chunks);
146
+ } else if (typeof responseAny.writeFile === "function") {
147
+ // SDK provides writeFile method - use a temp file
148
+ const tmpPath = path.join(os.tmpdir(), `feishu_${Date.now()}_${fileKey}`);
149
+ await responseAny.writeFile(tmpPath);
150
+ buffer = await fs.promises.readFile(tmpPath);
151
+ await fs.promises.unlink(tmpPath).catch(() => {}); // cleanup
152
+ } else if (typeof responseAny[Symbol.asyncIterator] === "function") {
153
+ // Response is an async iterable
154
+ const chunks: Buffer[] = [];
155
+ for await (const chunk of responseAny) {
156
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
157
+ }
158
+ buffer = Buffer.concat(chunks);
159
+ } else if (typeof responseAny.read === "function") {
160
+ // Response is a Readable stream
161
+ const chunks: Buffer[] = [];
162
+ for await (const chunk of responseAny as Readable) {
163
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
164
+ }
165
+ buffer = Buffer.concat(chunks);
166
+ } else {
167
+ // Debug: log what we actually received
168
+ const keys = Object.keys(responseAny);
169
+ const types = keys.map(k => `${k}: ${typeof responseAny[k]}`).join(", ");
170
+ throw new Error(
171
+ `Feishu message resource download failed: unexpected response format. Keys: [${types}]`,
172
+ );
173
+ }
174
+
175
+ return { buffer };
176
+ }
177
+
178
+ export type UploadImageResult = {
179
+ imageKey: string;
180
+ };
181
+
182
+ export type UploadFileResult = {
183
+ fileKey: string;
184
+ };
185
+
186
+ export type SendMediaResult = {
187
+ messageId: string;
188
+ chatId: string;
189
+ };
190
+
191
+ /**
192
+ * Upload an image to Feishu and get an image_key for sending.
193
+ * Supports: JPEG, PNG, WEBP, GIF, TIFF, BMP, ICO
194
+ */
195
+ export async function uploadImageFeishu(params: {
196
+ cfg: ClawdbotConfig;
197
+ image: Buffer | string; // Buffer or file path
198
+ imageType?: "message" | "avatar";
199
+ }): Promise<UploadImageResult> {
200
+ const { cfg, image, imageType = "message" } = params;
201
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
202
+ if (!feishuCfg) {
203
+ throw new Error("Feishu channel not configured");
204
+ }
205
+
206
+ const client = createFeishuClient(feishuCfg);
207
+
208
+ // SDK expects a Readable stream, not a Buffer
209
+ // Use type assertion since SDK actually accepts any Readable at runtime
210
+ const imageStream =
211
+ typeof image === "string" ? fs.createReadStream(image) : Readable.from(image);
212
+
213
+ const response = await client.im.image.create({
214
+ data: {
215
+ image_type: imageType,
216
+ image: imageStream as any,
217
+ },
218
+ });
219
+
220
+ // SDK v1.30+ returns data directly without code wrapper on success
221
+ // On error, it throws or returns { code, msg }
222
+ const responseAny = response as any;
223
+ if (responseAny.code !== undefined && responseAny.code !== 0) {
224
+ throw new Error(`Feishu image upload failed: ${responseAny.msg || `code ${responseAny.code}`}`);
225
+ }
226
+
227
+ const imageKey = responseAny.image_key ?? responseAny.data?.image_key;
228
+ if (!imageKey) {
229
+ throw new Error("Feishu image upload failed: no image_key returned");
230
+ }
231
+
232
+ return { imageKey };
233
+ }
234
+
235
+ /**
236
+ * Upload a file to Feishu and get a file_key for sending.
237
+ * Max file size: 30MB
238
+ */
239
+ export async function uploadFileFeishu(params: {
240
+ cfg: ClawdbotConfig;
241
+ file: Buffer | string; // Buffer or file path
242
+ fileName: string;
243
+ fileType: "opus" | "mp4" | "pdf" | "doc" | "xls" | "ppt" | "stream";
244
+ duration?: number; // Required for audio/video files, in milliseconds
245
+ }): Promise<UploadFileResult> {
246
+ const { cfg, file, fileName, fileType, duration } = params;
247
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
248
+ if (!feishuCfg) {
249
+ throw new Error("Feishu channel not configured");
250
+ }
251
+
252
+ const client = createFeishuClient(feishuCfg);
253
+
254
+ // SDK expects a Readable stream, not a Buffer
255
+ // Use type assertion since SDK actually accepts any Readable at runtime
256
+ const fileStream =
257
+ typeof file === "string" ? fs.createReadStream(file) : Readable.from(file);
258
+
259
+ const response = await client.im.file.create({
260
+ data: {
261
+ file_type: fileType,
262
+ file_name: fileName,
263
+ file: fileStream as any,
264
+ ...(duration !== undefined && { duration }),
265
+ },
266
+ });
267
+
268
+ // SDK v1.30+ returns data directly without code wrapper on success
269
+ const responseAny = response as any;
270
+ if (responseAny.code !== undefined && responseAny.code !== 0) {
271
+ throw new Error(`Feishu file upload failed: ${responseAny.msg || `code ${responseAny.code}`}`);
272
+ }
273
+
274
+ const fileKey = responseAny.file_key ?? responseAny.data?.file_key;
275
+ if (!fileKey) {
276
+ throw new Error("Feishu file upload failed: no file_key returned");
277
+ }
278
+
279
+ return { fileKey };
280
+ }
281
+
282
+ /**
283
+ * Send an image message using an image_key
284
+ */
285
+ export async function sendImageFeishu(params: {
286
+ cfg: ClawdbotConfig;
287
+ to: string;
288
+ imageKey: string;
289
+ replyToMessageId?: string;
290
+ }): Promise<SendMediaResult> {
291
+ const { cfg, to, imageKey, replyToMessageId } = params;
292
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
293
+ if (!feishuCfg) {
294
+ throw new Error("Feishu channel not configured");
295
+ }
296
+
297
+ const client = createFeishuClient(feishuCfg);
298
+ const receiveId = normalizeFeishuTarget(to);
299
+ if (!receiveId) {
300
+ throw new Error(`Invalid Feishu target: ${to}`);
301
+ }
302
+
303
+ const receiveIdType = resolveReceiveIdType(receiveId);
304
+ const content = JSON.stringify({ image_key: imageKey });
305
+
306
+ if (replyToMessageId) {
307
+ const response = await client.im.message.reply({
308
+ path: { message_id: replyToMessageId },
309
+ data: {
310
+ content,
311
+ msg_type: "image",
312
+ },
313
+ });
314
+
315
+ if (response.code !== 0) {
316
+ throw new Error(`Feishu image reply failed: ${response.msg || `code ${response.code}`}`);
317
+ }
318
+
319
+ return {
320
+ messageId: response.data?.message_id ?? "unknown",
321
+ chatId: receiveId,
322
+ };
323
+ }
324
+
325
+ const response = await client.im.message.create({
326
+ params: { receive_id_type: receiveIdType },
327
+ data: {
328
+ receive_id: receiveId,
329
+ content,
330
+ msg_type: "image",
331
+ },
332
+ });
333
+
334
+ if (response.code !== 0) {
335
+ throw new Error(`Feishu image send failed: ${response.msg || `code ${response.code}`}`);
336
+ }
337
+
338
+ return {
339
+ messageId: response.data?.message_id ?? "unknown",
340
+ chatId: receiveId,
341
+ };
342
+ }
343
+
344
+ /**
345
+ * Send a file message using a file_key
346
+ */
347
+ export async function sendFileFeishu(params: {
348
+ cfg: ClawdbotConfig;
349
+ to: string;
350
+ fileKey: string;
351
+ replyToMessageId?: string;
352
+ }): Promise<SendMediaResult> {
353
+ const { cfg, to, fileKey, replyToMessageId } = params;
354
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
355
+ if (!feishuCfg) {
356
+ throw new Error("Feishu channel not configured");
357
+ }
358
+
359
+ const client = createFeishuClient(feishuCfg);
360
+ const receiveId = normalizeFeishuTarget(to);
361
+ if (!receiveId) {
362
+ throw new Error(`Invalid Feishu target: ${to}`);
363
+ }
364
+
365
+ const receiveIdType = resolveReceiveIdType(receiveId);
366
+ const content = JSON.stringify({ file_key: fileKey });
367
+
368
+ if (replyToMessageId) {
369
+ const response = await client.im.message.reply({
370
+ path: { message_id: replyToMessageId },
371
+ data: {
372
+ content,
373
+ msg_type: "file",
374
+ },
375
+ });
376
+
377
+ if (response.code !== 0) {
378
+ throw new Error(`Feishu file reply failed: ${response.msg || `code ${response.code}`}`);
379
+ }
380
+
381
+ return {
382
+ messageId: response.data?.message_id ?? "unknown",
383
+ chatId: receiveId,
384
+ };
385
+ }
386
+
387
+ const response = await client.im.message.create({
388
+ params: { receive_id_type: receiveIdType },
389
+ data: {
390
+ receive_id: receiveId,
391
+ content,
392
+ msg_type: "file",
393
+ },
394
+ });
395
+
396
+ if (response.code !== 0) {
397
+ throw new Error(`Feishu file send failed: ${response.msg || `code ${response.code}`}`);
398
+ }
399
+
400
+ return {
401
+ messageId: response.data?.message_id ?? "unknown",
402
+ chatId: receiveId,
403
+ };
404
+ }
405
+
406
+ /**
407
+ * Helper to detect file type from extension
408
+ */
409
+ export function detectFileType(
410
+ fileName: string,
411
+ ): "opus" | "mp4" | "pdf" | "doc" | "xls" | "ppt" | "stream" {
412
+ const ext = path.extname(fileName).toLowerCase();
413
+ switch (ext) {
414
+ case ".opus":
415
+ case ".ogg":
416
+ return "opus";
417
+ case ".mp4":
418
+ case ".mov":
419
+ case ".avi":
420
+ return "mp4";
421
+ case ".pdf":
422
+ return "pdf";
423
+ case ".doc":
424
+ case ".docx":
425
+ return "doc";
426
+ case ".xls":
427
+ case ".xlsx":
428
+ return "xls";
429
+ case ".ppt":
430
+ case ".pptx":
431
+ return "ppt";
432
+ default:
433
+ return "stream";
434
+ }
435
+ }
436
+
437
+ /**
438
+ * Check if a string is a local file path (not a URL)
439
+ */
440
+ function isLocalPath(urlOrPath: string): boolean {
441
+ // Starts with / or ~ or drive letter (Windows)
442
+ if (urlOrPath.startsWith("/") || urlOrPath.startsWith("~") || /^[a-zA-Z]:/.test(urlOrPath)) {
443
+ return true;
444
+ }
445
+ // Try to parse as URL - if it fails or has no protocol, it's likely a local path
446
+ try {
447
+ const url = new URL(urlOrPath);
448
+ return url.protocol === "file:";
449
+ } catch {
450
+ return true; // Not a valid URL, treat as local path
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Upload and send media (image or file) from URL, local path, or buffer
456
+ */
457
+ export async function sendMediaFeishu(params: {
458
+ cfg: ClawdbotConfig;
459
+ to: string;
460
+ mediaUrl?: string;
461
+ mediaBuffer?: Buffer;
462
+ fileName?: string;
463
+ replyToMessageId?: string;
464
+ }): Promise<SendMediaResult> {
465
+ const { cfg, to, mediaUrl, mediaBuffer, fileName, replyToMessageId } = params;
466
+
467
+ let buffer: Buffer;
468
+ let name: string;
469
+
470
+ if (mediaBuffer) {
471
+ buffer = mediaBuffer;
472
+ name = fileName ?? "file";
473
+ } else if (mediaUrl) {
474
+ if (isLocalPath(mediaUrl)) {
475
+ // Local file path - read directly
476
+ const filePath = mediaUrl.startsWith("~")
477
+ ? mediaUrl.replace("~", process.env.HOME ?? "")
478
+ : mediaUrl.replace("file://", "");
479
+
480
+ if (!fs.existsSync(filePath)) {
481
+ throw new Error(`Local file not found: ${filePath}`);
482
+ }
483
+ buffer = fs.readFileSync(filePath);
484
+ name = fileName ?? path.basename(filePath);
485
+ } else {
486
+ // Remote URL - fetch
487
+ const response = await fetch(mediaUrl);
488
+ if (!response.ok) {
489
+ throw new Error(`Failed to fetch media from URL: ${response.status}`);
490
+ }
491
+ buffer = Buffer.from(await response.arrayBuffer());
492
+ name = fileName ?? (path.basename(new URL(mediaUrl).pathname) || "file");
493
+ }
494
+ } else {
495
+ throw new Error("Either mediaUrl or mediaBuffer must be provided");
496
+ }
497
+
498
+ // Determine if it's an image based on extension
499
+ const ext = path.extname(name).toLowerCase();
500
+ const isImage = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".ico", ".tiff"].includes(ext);
501
+
502
+ if (isImage) {
503
+ const { imageKey } = await uploadImageFeishu({ cfg, image: buffer });
504
+ return sendImageFeishu({ cfg, to, imageKey, replyToMessageId });
505
+ } else {
506
+ const fileType = detectFileType(name);
507
+ const { fileKey } = await uploadFileFeishu({
508
+ cfg,
509
+ file: buffer,
510
+ fileName: name,
511
+ fileType,
512
+ });
513
+ return sendFileFeishu({ cfg, to, fileKey, replyToMessageId });
514
+ }
515
+ }
package/src/monitor.ts ADDED
@@ -0,0 +1,151 @@
1
+ import * as Lark from "@larksuiteoapi/node-sdk";
2
+ import type { ClawdbotConfig, RuntimeEnv, HistoryEntry } from "clawdbot/plugin-sdk";
3
+ import type { FeishuConfig } from "./types.js";
4
+ import { createFeishuWSClient, createEventDispatcher } from "./client.js";
5
+ import { resolveFeishuCredentials } from "./accounts.js";
6
+ import { handleFeishuMessage, type FeishuMessageEvent, type FeishuBotAddedEvent } from "./bot.js";
7
+ import { probeFeishu } from "./probe.js";
8
+
9
+ export type MonitorFeishuOpts = {
10
+ config?: ClawdbotConfig;
11
+ runtime?: RuntimeEnv;
12
+ abortSignal?: AbortSignal;
13
+ accountId?: string;
14
+ };
15
+
16
+ let currentWsClient: Lark.WSClient | null = null;
17
+ let botOpenId: string | undefined;
18
+
19
+ async function fetchBotOpenId(cfg: FeishuConfig): Promise<string | undefined> {
20
+ try {
21
+ const result = await probeFeishu(cfg);
22
+ return result.ok ? result.botOpenId : undefined;
23
+ } catch {
24
+ return undefined;
25
+ }
26
+ }
27
+
28
+ export async function monitorFeishuProvider(opts: MonitorFeishuOpts = {}): Promise<void> {
29
+ const cfg = opts.config;
30
+ if (!cfg) {
31
+ throw new Error("Config is required for Feishu monitor");
32
+ }
33
+
34
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
35
+ const creds = resolveFeishuCredentials(feishuCfg);
36
+ if (!creds) {
37
+ throw new Error("Feishu credentials not configured (appId, appSecret required)");
38
+ }
39
+
40
+ const log = opts.runtime?.log ?? console.log;
41
+ const error = opts.runtime?.error ?? console.error;
42
+
43
+ if (feishuCfg) {
44
+ botOpenId = await fetchBotOpenId(feishuCfg);
45
+ log(`feishu: bot open_id resolved: ${botOpenId ?? "unknown"}`);
46
+ }
47
+
48
+ const connectionMode = feishuCfg?.connectionMode ?? "websocket";
49
+
50
+ if (connectionMode === "websocket") {
51
+ return monitorWebSocket({ cfg, feishuCfg: feishuCfg!, runtime: opts.runtime, abortSignal: opts.abortSignal });
52
+ }
53
+
54
+ log("feishu: webhook mode not implemented in monitor, use HTTP server directly");
55
+ }
56
+
57
+ async function monitorWebSocket(params: {
58
+ cfg: ClawdbotConfig;
59
+ feishuCfg: FeishuConfig;
60
+ runtime?: RuntimeEnv;
61
+ abortSignal?: AbortSignal;
62
+ }): Promise<void> {
63
+ const { cfg, feishuCfg, runtime, abortSignal } = params;
64
+ const log = runtime?.log ?? console.log;
65
+ const error = runtime?.error ?? console.error;
66
+
67
+ log("feishu: starting WebSocket connection...");
68
+
69
+ const wsClient = createFeishuWSClient(feishuCfg);
70
+ currentWsClient = wsClient;
71
+
72
+ const chatHistories = new Map<string, HistoryEntry[]>();
73
+
74
+ const eventDispatcher = createEventDispatcher(feishuCfg);
75
+
76
+ eventDispatcher.register({
77
+ "im.message.receive_v1": async (data) => {
78
+ try {
79
+ const event = data as unknown as FeishuMessageEvent;
80
+ await handleFeishuMessage({
81
+ cfg,
82
+ event,
83
+ botOpenId,
84
+ runtime,
85
+ chatHistories,
86
+ });
87
+ } catch (err) {
88
+ error(`feishu: error handling message event: ${String(err)}`);
89
+ }
90
+ },
91
+ "im.message.message_read_v1": async () => {
92
+ // Ignore read receipts
93
+ },
94
+ "im.chat.member.bot.added_v1": async (data) => {
95
+ try {
96
+ const event = data as unknown as FeishuBotAddedEvent;
97
+ log(`feishu: bot added to chat ${event.chat_id}`);
98
+ } catch (err) {
99
+ error(`feishu: error handling bot added event: ${String(err)}`);
100
+ }
101
+ },
102
+ "im.chat.member.bot.deleted_v1": async (data) => {
103
+ try {
104
+ const event = data as unknown as { chat_id: string };
105
+ log(`feishu: bot removed from chat ${event.chat_id}`);
106
+ } catch (err) {
107
+ error(`feishu: error handling bot removed event: ${String(err)}`);
108
+ }
109
+ },
110
+ });
111
+
112
+ return new Promise((resolve, reject) => {
113
+ const cleanup = () => {
114
+ if (currentWsClient === wsClient) {
115
+ currentWsClient = null;
116
+ }
117
+ };
118
+
119
+ const handleAbort = () => {
120
+ log("feishu: abort signal received, stopping WebSocket client");
121
+ cleanup();
122
+ resolve();
123
+ };
124
+
125
+ if (abortSignal?.aborted) {
126
+ cleanup();
127
+ resolve();
128
+ return;
129
+ }
130
+
131
+ abortSignal?.addEventListener("abort", handleAbort, { once: true });
132
+
133
+ try {
134
+ wsClient.start({
135
+ eventDispatcher,
136
+ });
137
+
138
+ log("feishu: WebSocket client started");
139
+ } catch (err) {
140
+ cleanup();
141
+ abortSignal?.removeEventListener("abort", handleAbort);
142
+ reject(err);
143
+ }
144
+ });
145
+ }
146
+
147
+ export function stopFeishuMonitor(): void {
148
+ if (currentWsClient) {
149
+ currentWsClient = null;
150
+ }
151
+ }