@kodelyth/feishu 2026.5.39 → 2026.6.1

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.
Files changed (47) hide show
  1. package/dist/accounts-D0ow-lRb.js +429 -0
  2. package/dist/api.js +2308 -0
  3. package/dist/app-registration-DBSnysKJ.js +184 -0
  4. package/dist/audio-preflight.runtime-Dpjbn-7r.js +7 -0
  5. package/dist/channel-13WQvQ0u.js +2115 -0
  6. package/dist/channel-entry.js +22 -0
  7. package/dist/channel-plugin-api.js +2 -0
  8. package/dist/channel.runtime-JMJonrJ4.js +729 -0
  9. package/dist/client-D1pzbBGo.js +157 -0
  10. package/dist/contract-api.js +9 -0
  11. package/dist/conversation-id-_58ecqlx.js +139 -0
  12. package/dist/drive-CgHOluXx.js +883 -0
  13. package/dist/index.js +68 -0
  14. package/dist/monitor-oWptK0zL.js +60 -0
  15. package/dist/monitor.account-DHaWlslg.js +5207 -0
  16. package/dist/monitor.state-C211a4tX.js +100 -0
  17. package/dist/probe-CF4duEpK.js +149 -0
  18. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  19. package/dist/runtime-DSh5rL_d.js +8 -0
  20. package/dist/runtime-api.js +14 -0
  21. package/dist/secret-contract-NSee-WzN.js +119 -0
  22. package/dist/secret-contract-api.js +2 -0
  23. package/dist/security-audit-DWVC0vSK.js +11 -0
  24. package/dist/security-audit-shared-Dpcwxeft.js +38 -0
  25. package/dist/security-contract-api.js +2 -0
  26. package/dist/send-DfZuV4Fi.js +1212 -0
  27. package/dist/session-conversation-Duaukbnl.js +27 -0
  28. package/dist/session-key-api.js +2 -0
  29. package/dist/setup-api.js +2 -0
  30. package/dist/setup-entry.js +15 -0
  31. package/dist/subagent-hooks-Dtegs0kh.js +235 -0
  32. package/dist/subagent-hooks-api.js +23 -0
  33. package/dist/targets-DFskxX4p.js +48 -0
  34. package/dist/thread-bindings-DI7lVSOE.js +222 -0
  35. package/package.json +20 -7
  36. package/api.js +0 -7
  37. package/channel-entry.js +0 -7
  38. package/channel-plugin-api.js +0 -7
  39. package/contract-api.js +0 -7
  40. package/index.js +0 -7
  41. package/runtime-api.js +0 -7
  42. package/secret-contract-api.js +0 -7
  43. package/security-contract-api.js +0 -7
  44. package/session-key-api.js +0 -7
  45. package/setup-api.js +0 -7
  46. package/setup-entry.js +0 -7
  47. package/subagent-hooks-api.js +0 -7
@@ -0,0 +1,1212 @@
1
+ import { i as resolveReceiveIdType, r as normalizeFeishuTarget } from "./targets-DFskxX4p.js";
2
+ import { c as createFeishuApiError, f as isRecord$2, g as requestFeishuApi, s as resolveFeishuRuntimeAccount } from "./accounts-D0ow-lRb.js";
3
+ import { c as toFeishuSendResult, o as assertFeishuMessageApiSuccess, s as resolveFeishuReceiptKind } from "./channel-13WQvQ0u.js";
4
+ import { t as getFeishuRuntime } from "./runtime-DSh5rL_d.js";
5
+ import { r as createFeishuClient } from "./client-D1pzbBGo.js";
6
+ import { normalizeLowercaseStringOrEmpty, normalizeOptionalLowercaseString } from "klaw/plugin-sdk/string-coerce-runtime";
7
+ import { convertMarkdownTables } from "klaw/plugin-sdk/text-chunking";
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { mediaKindFromMime } from "klaw/plugin-sdk/media-mime";
11
+ import { MEDIA_FFMPEG_MAX_AUDIO_DURATION_SECS, runFfmpeg } from "klaw/plugin-sdk/media-runtime";
12
+ import { readRegularFile, writeExternalFileWithinRoot } from "klaw/plugin-sdk/security-runtime";
13
+ import { Readable } from "node:stream";
14
+ import { saveMediaBuffer, saveMediaStream } from "klaw/plugin-sdk/media-store";
15
+ import "klaw/plugin-sdk/response-limit-runtime";
16
+ import { resolvePreferredKlawTmpDir, withTempDownloadPath, withTempWorkspace } from "klaw/plugin-sdk/temp-path";
17
+ import { resolveMarkdownTableMode } from "klaw/plugin-sdk/markdown-table-runtime";
18
+ //#region extensions/feishu/src/external-keys.ts
19
+ const CONTROL_CHARS_RE = /\p{Cc}/u;
20
+ const MAX_EXTERNAL_KEY_LENGTH = 512;
21
+ function normalizeFeishuExternalKey(value) {
22
+ if (typeof value !== "string") return;
23
+ const normalized = value.trim();
24
+ if (!normalized || normalized.length > MAX_EXTERNAL_KEY_LENGTH) return;
25
+ if (CONTROL_CHARS_RE.test(normalized)) return;
26
+ if (normalized.includes("/") || normalized.includes("\\") || normalized.includes("..")) return;
27
+ return normalized;
28
+ }
29
+ //#endregion
30
+ //#region extensions/feishu/src/send-target.ts
31
+ function resolveFeishuSendTarget(params) {
32
+ const target = params.to.trim();
33
+ const account = resolveFeishuRuntimeAccount({
34
+ cfg: params.cfg,
35
+ accountId: params.accountId
36
+ });
37
+ if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
38
+ const client = createFeishuClient(account);
39
+ const receiveId = normalizeFeishuTarget(target);
40
+ if (!receiveId) throw new Error(`Invalid Feishu target: ${params.to}`);
41
+ return {
42
+ client,
43
+ receiveId,
44
+ receiveIdType: resolveReceiveIdType(target.replace(/^(feishu|lark):/i, ""))
45
+ };
46
+ }
47
+ //#endregion
48
+ //#region extensions/feishu/src/media.ts
49
+ const FEISHU_MEDIA_HTTP_TIMEOUT_MS = 12e4;
50
+ const FEISHU_VOICE_FILE_NAME = "voice.ogg";
51
+ const FEISHU_VOICE_SAMPLE_RATE_HZ = 48e3;
52
+ const FEISHU_VOICE_BITRATE = "64k";
53
+ const FEISHU_TRANSCODABLE_AUDIO_EXTS = new Set([
54
+ ".aac",
55
+ ".aiff",
56
+ ".alac",
57
+ ".amr",
58
+ ".caf",
59
+ ".flac",
60
+ ".m4a",
61
+ ".mp3",
62
+ ".oga",
63
+ ".wav",
64
+ ".webm",
65
+ ".wma"
66
+ ]);
67
+ function createConfiguredFeishuMediaClient(params) {
68
+ const account = resolveFeishuRuntimeAccount({
69
+ cfg: params.cfg,
70
+ accountId: params.accountId
71
+ });
72
+ if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
73
+ return {
74
+ account,
75
+ client: createFeishuClient({
76
+ ...account,
77
+ httpTimeoutMs: FEISHU_MEDIA_HTTP_TIMEOUT_MS
78
+ })
79
+ };
80
+ }
81
+ function asHeaderMap(value) {
82
+ if (!value) return;
83
+ const entries = Object.entries(value);
84
+ if (entries.every(([, entry]) => typeof entry === "string" || Array.isArray(entry))) return Object.fromEntries(entries);
85
+ }
86
+ function extractFeishuUploadKey(response, params) {
87
+ if (!response) throw new Error(`${params.errorPrefix}: empty response`);
88
+ const wrappedResponse = response;
89
+ if (wrappedResponse.code !== void 0 && wrappedResponse.code !== 0) throw new Error(`${params.errorPrefix}: ${wrappedResponse.msg || `code ${wrappedResponse.code}`}`);
90
+ const key = params.key === "image_key" ? wrappedResponse.image_key ?? wrappedResponse.data?.image_key : wrappedResponse.file_key ?? wrappedResponse.data?.file_key;
91
+ if (!key) throw new Error(`${params.errorPrefix}: no ${params.key} returned`);
92
+ return key;
93
+ }
94
+ function readHeaderValue(headers, name) {
95
+ if (!headers) return;
96
+ for (const [key, value] of Object.entries(headers)) {
97
+ if (normalizeLowercaseStringOrEmpty(key) !== normalizeLowercaseStringOrEmpty(name)) continue;
98
+ if (typeof value === "string" && value.trim()) return value.trim();
99
+ if (Array.isArray(value)) {
100
+ const first = value.find((entry) => typeof entry === "string" && entry.trim());
101
+ if (typeof first === "string") return first.trim();
102
+ }
103
+ }
104
+ }
105
+ function readHttpStatusFromError(error) {
106
+ if (!error || typeof error !== "object") return;
107
+ const response = error.response;
108
+ if (response && typeof response === "object") {
109
+ const status = response.status;
110
+ if (typeof status === "number") return status;
111
+ }
112
+ const status = error.status;
113
+ return typeof status === "number" ? status : void 0;
114
+ }
115
+ function isHttpStatusError(error, status) {
116
+ return readHttpStatusFromError(error) === status;
117
+ }
118
+ function containsEastAsianScript(value) {
119
+ return /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u.test(value);
120
+ }
121
+ function recoverUtf8FileNameFromLatin1Header(value) {
122
+ const recovered = Buffer.from(value, "latin1").toString("utf8");
123
+ if (recovered !== value && !recovered.includes("�") && containsEastAsianScript(recovered)) return recovered;
124
+ return value;
125
+ }
126
+ function decodeDispositionFileName(value) {
127
+ const utf8Match = value.match(/filename\*=UTF-8''([^;]+)/i);
128
+ if (utf8Match?.[1]) try {
129
+ return decodeURIComponent(utf8Match[1].trim().replace(/^"(.*)"$/, "$1"));
130
+ } catch {
131
+ return utf8Match[1].trim().replace(/^"(.*)"$/, "$1");
132
+ }
133
+ const plainFileName = value.match(/filename="?([^";]+)"?/i)?.[1]?.trim();
134
+ return plainFileName ? recoverUtf8FileNameFromLatin1Header(plainFileName) : void 0;
135
+ }
136
+ function extractFeishuDownloadMetadata(response) {
137
+ const responseWithOptionalFields = response;
138
+ const headers = asHeaderMap(responseWithOptionalFields.headers) ?? asHeaderMap(responseWithOptionalFields.header);
139
+ const contentType = readHeaderValue(headers, "content-type") ?? responseWithOptionalFields.contentType ?? responseWithOptionalFields.mime_type ?? responseWithOptionalFields.data?.contentType ?? responseWithOptionalFields.data?.mime_type;
140
+ const disposition = readHeaderValue(headers, "content-disposition");
141
+ return {
142
+ contentType,
143
+ fileName: (disposition ? decodeDispositionFileName(disposition) : void 0) ?? responseWithOptionalFields.file_name ?? responseWithOptionalFields.fileName ?? responseWithOptionalFields.data?.file_name ?? responseWithOptionalFields.data?.fileName
144
+ };
145
+ }
146
+ function mediaLimitError(maxBytes) {
147
+ return /* @__PURE__ */ new Error(`Media exceeds ${Math.round(maxBytes / (1024 * 1024))}MB limit`);
148
+ }
149
+ async function saveFeishuResponseMedia(params) {
150
+ const { response, maxBytes, contentType, fileName } = params;
151
+ if (Buffer.isBuffer(response)) return saveMediaBuffer(response, contentType, "inbound", maxBytes, fileName);
152
+ if (response instanceof ArrayBuffer) return saveMediaBuffer(Buffer.from(response), contentType, "inbound", maxBytes, fileName);
153
+ const responseWithOptionalFields = response;
154
+ if (responseWithOptionalFields.code !== void 0 && responseWithOptionalFields.code !== 0) throw new Error(`${params.errorPrefix}: ${responseWithOptionalFields.msg || `code ${responseWithOptionalFields.code}`}`);
155
+ if (responseWithOptionalFields.data && Buffer.isBuffer(responseWithOptionalFields.data)) return saveMediaBuffer(responseWithOptionalFields.data, contentType, "inbound", maxBytes, fileName);
156
+ if (responseWithOptionalFields.data instanceof ArrayBuffer) return saveMediaBuffer(Buffer.from(responseWithOptionalFields.data), contentType, "inbound", maxBytes, fileName);
157
+ if (typeof response.getReadableStream === "function") return saveMediaStream(response.getReadableStream(), contentType, "inbound", maxBytes, fileName);
158
+ if (typeof response.writeFile === "function") return await withTempDownloadPath({ prefix: params.tmpDirPrefix }, async (tmpPath) => {
159
+ await response.writeFile(tmpPath);
160
+ if ((await fs.promises.stat(tmpPath)).size > maxBytes) throw mediaLimitError(maxBytes);
161
+ return await saveMediaStream(fs.createReadStream(tmpPath), contentType, "inbound", maxBytes, fileName);
162
+ });
163
+ if (responseWithOptionalFields[Symbol.asyncIterator]) return saveMediaStream(responseWithOptionalFields, contentType, "inbound", maxBytes, fileName);
164
+ if (response instanceof Readable) return saveMediaStream(response, contentType, "inbound", maxBytes, fileName);
165
+ const keys = Object.keys(response);
166
+ throw new Error(`${params.errorPrefix}: unexpected response format. Keys: [${keys.join(", ")}]`);
167
+ }
168
+ async function saveMessageResourceWithType(params) {
169
+ const response = await params.client.im.messageResource.get({
170
+ path: {
171
+ message_id: params.messageId,
172
+ file_key: params.fileKey
173
+ },
174
+ params: { type: params.type }
175
+ });
176
+ const meta = extractFeishuDownloadMetadata(response);
177
+ return {
178
+ saved: await saveFeishuResponseMedia({
179
+ response,
180
+ tmpDirPrefix: "klaw-feishu-resource-",
181
+ errorPrefix: "Feishu message resource download failed",
182
+ maxBytes: params.maxBytes,
183
+ contentType: meta.contentType,
184
+ fileName: meta.fileName ?? params.originalFilename
185
+ }),
186
+ ...meta
187
+ };
188
+ }
189
+ async function saveMessageResourceFeishu(params) {
190
+ const { cfg, messageId, fileKey, type, accountId, maxBytes, originalFilename } = params;
191
+ const normalizedFileKey = normalizeFeishuExternalKey(fileKey);
192
+ if (!normalizedFileKey) throw new Error("Feishu message resource download failed: invalid file_key");
193
+ const { client } = createConfiguredFeishuMediaClient({
194
+ cfg,
195
+ accountId
196
+ });
197
+ try {
198
+ return await saveMessageResourceWithType({
199
+ client,
200
+ messageId,
201
+ fileKey: normalizedFileKey,
202
+ type,
203
+ maxBytes,
204
+ originalFilename
205
+ });
206
+ } catch (err) {
207
+ if (type !== "file" || !isHttpStatusError(err, 502)) throw err;
208
+ try {
209
+ return await saveMessageResourceWithType({
210
+ client,
211
+ messageId,
212
+ fileKey: normalizedFileKey,
213
+ type: "media",
214
+ maxBytes,
215
+ originalFilename
216
+ });
217
+ } catch {
218
+ throw err;
219
+ }
220
+ }
221
+ }
222
+ /**
223
+ * Upload an image to Feishu and get an image_key for sending.
224
+ * Supports: JPEG, PNG, WEBP, GIF, TIFF, BMP, ICO
225
+ */
226
+ async function uploadImageFeishu(params) {
227
+ const { cfg, image, imageType = "message", accountId } = params;
228
+ const { client } = createConfiguredFeishuMediaClient({
229
+ cfg,
230
+ accountId
231
+ });
232
+ const imageData = typeof image === "string" ? (await readRegularFile({ filePath: image })).buffer : image;
233
+ return { imageKey: extractFeishuUploadKey(await requestFeishuApi(() => client.im.image.create({ data: {
234
+ image_type: imageType,
235
+ image: imageData
236
+ } }), "Feishu image upload failed", { includeNestedErrorLogId: true }), {
237
+ key: "image_key",
238
+ errorPrefix: "Feishu image upload failed"
239
+ }) };
240
+ }
241
+ /**
242
+ * Sanitize a filename for safe use in Feishu multipart/form-data uploads.
243
+ * Strips control characters and multipart-injection vectors (CWE-93) while
244
+ * preserving the original UTF-8 display name (Chinese, emoji, etc.).
245
+ *
246
+ * Previous versions percent-encoded non-ASCII characters, but the Feishu
247
+ * `im.file.create` API uses `file_name` as a literal display name — it does
248
+ * NOT decode percent-encoding — so encoded filenames appeared as garbled text
249
+ * in chat (regression in v2026.3.2).
250
+ */
251
+ function sanitizeFileNameForUpload(fileName) {
252
+ return fileName.replace(/[\p{Cc}"\\]/gu, "_");
253
+ }
254
+ /**
255
+ * Upload a file to Feishu and get a file_key for sending.
256
+ * Max file size: 30MB
257
+ */
258
+ async function uploadFileFeishu(params) {
259
+ const { cfg, file, fileName, fileType, duration, accountId } = params;
260
+ const { client } = createConfiguredFeishuMediaClient({
261
+ cfg,
262
+ accountId
263
+ });
264
+ const fileData = typeof file === "string" ? (await readRegularFile({ filePath: file })).buffer : file;
265
+ const safeFileName = sanitizeFileNameForUpload(fileName);
266
+ return { fileKey: extractFeishuUploadKey(await requestFeishuApi(() => client.im.file.create({ data: {
267
+ file_type: fileType,
268
+ file_name: safeFileName,
269
+ file: fileData,
270
+ ...duration !== void 0 && { duration }
271
+ } }), "Feishu file upload failed", { includeNestedErrorLogId: true }), {
272
+ key: "file_key",
273
+ errorPrefix: "Feishu file upload failed"
274
+ }) };
275
+ }
276
+ /**
277
+ * Send an image message using an image_key
278
+ */
279
+ async function sendImageFeishu(params) {
280
+ const { cfg, to, imageKey, replyToMessageId, replyInThread, accountId } = params;
281
+ const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({
282
+ cfg,
283
+ to,
284
+ accountId
285
+ });
286
+ const content = JSON.stringify({ image_key: imageKey });
287
+ if (replyToMessageId) {
288
+ const response = await requestFeishuApi(() => client.im.message.reply({
289
+ path: { message_id: replyToMessageId },
290
+ data: {
291
+ content,
292
+ msg_type: "image",
293
+ ...replyInThread ? { reply_in_thread: true } : {}
294
+ }
295
+ }), "Feishu image reply failed", { includeNestedErrorLogId: true });
296
+ assertFeishuMessageApiSuccess(response, "Feishu image reply failed");
297
+ return toFeishuSendResult(response, receiveId, "media");
298
+ }
299
+ const response = await requestFeishuApi(() => client.im.message.create({
300
+ params: { receive_id_type: receiveIdType },
301
+ data: {
302
+ receive_id: receiveId,
303
+ content,
304
+ msg_type: "image"
305
+ }
306
+ }), "Feishu image send failed", { includeNestedErrorLogId: true });
307
+ assertFeishuMessageApiSuccess(response, "Feishu image send failed");
308
+ return toFeishuSendResult(response, receiveId, "media");
309
+ }
310
+ /**
311
+ * Send a file message using a file_key
312
+ */
313
+ async function sendFileFeishu(params) {
314
+ const { cfg, to, fileKey, replyToMessageId, replyInThread, accountId } = params;
315
+ const msgType = params.msgType ?? "file";
316
+ const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({
317
+ cfg,
318
+ to,
319
+ accountId
320
+ });
321
+ const content = JSON.stringify({ file_key: fileKey });
322
+ if (replyToMessageId) {
323
+ const response = await requestFeishuApi(() => client.im.message.reply({
324
+ path: { message_id: replyToMessageId },
325
+ data: {
326
+ content,
327
+ msg_type: msgType,
328
+ ...replyInThread ? { reply_in_thread: true } : {}
329
+ }
330
+ }), "Feishu file reply failed", { includeNestedErrorLogId: true });
331
+ assertFeishuMessageApiSuccess(response, "Feishu file reply failed");
332
+ return toFeishuSendResult(response, receiveId, resolveFeishuReceiptKind(msgType));
333
+ }
334
+ const response = await requestFeishuApi(() => client.im.message.create({
335
+ params: { receive_id_type: receiveIdType },
336
+ data: {
337
+ receive_id: receiveId,
338
+ content,
339
+ msg_type: msgType
340
+ }
341
+ }), "Feishu file send failed", { includeNestedErrorLogId: true });
342
+ assertFeishuMessageApiSuccess(response, "Feishu file send failed");
343
+ return toFeishuSendResult(response, receiveId, resolveFeishuReceiptKind(msgType));
344
+ }
345
+ /**
346
+ * Helper to detect file type from extension
347
+ */
348
+ function detectFileType(fileName) {
349
+ switch (normalizeLowercaseStringOrEmpty(path.extname(fileName))) {
350
+ case ".opus":
351
+ case ".ogg": return "opus";
352
+ case ".mp4":
353
+ case ".mov":
354
+ case ".avi": return "mp4";
355
+ case ".pdf": return "pdf";
356
+ case ".doc":
357
+ case ".docx": return "doc";
358
+ case ".xls":
359
+ case ".xlsx": return "xls";
360
+ case ".ppt":
361
+ case ".pptx": return "ppt";
362
+ default: return "stream";
363
+ }
364
+ }
365
+ function resolveFeishuOutboundMediaKind(params) {
366
+ const { fileName, contentType } = params;
367
+ const ext = normalizeLowercaseStringOrEmpty(path.extname(fileName));
368
+ const mimeKind = mediaKindFromMime(contentType);
369
+ if ([
370
+ ".jpg",
371
+ ".jpeg",
372
+ ".png",
373
+ ".gif",
374
+ ".webp",
375
+ ".bmp",
376
+ ".ico",
377
+ ".tiff"
378
+ ].includes(ext) || mimeKind === "image") return { msgType: "image" };
379
+ if (ext === ".opus" || ext === ".ogg" || contentType === "audio/ogg" || contentType === "audio/opus") return {
380
+ fileType: "opus",
381
+ msgType: "audio"
382
+ };
383
+ if ([
384
+ ".mp4",
385
+ ".mov",
386
+ ".avi"
387
+ ].includes(ext) || contentType === "video/mp4" || contentType === "video/quicktime" || contentType === "video/x-msvideo") return {
388
+ fileType: "mp4",
389
+ msgType: "media"
390
+ };
391
+ const fileType = detectFileType(fileName);
392
+ return {
393
+ fileType,
394
+ msgType: fileType === "stream" ? "file" : fileType === "opus" ? "audio" : fileType === "mp4" ? "media" : "file"
395
+ };
396
+ }
397
+ function isFeishuNativeVoiceAudio(params) {
398
+ const ext = normalizeLowercaseStringOrEmpty(path.extname(params.fileName));
399
+ const contentType = normalizeLowercaseStringOrEmpty(params.contentType);
400
+ return ext === ".opus" || ext === ".ogg" || contentType === "audio/ogg" || contentType === "audio/opus";
401
+ }
402
+ function normalizeMediaNameForExtension(raw) {
403
+ try {
404
+ return new URL(raw).pathname;
405
+ } catch {
406
+ return raw.split(/[?#]/, 1)[0] ?? raw;
407
+ }
408
+ }
409
+ function shouldSuppressFeishuTextForVoiceMedia(params) {
410
+ if (params.audioAsVoice === true) return true;
411
+ if (params.fileName && isFeishuNativeVoiceAudio({
412
+ fileName: params.fileName,
413
+ contentType: params.contentType
414
+ })) return true;
415
+ if (!params.mediaUrl) return false;
416
+ return isFeishuNativeVoiceAudio({
417
+ fileName: normalizeMediaNameForExtension(params.mediaUrl),
418
+ contentType: params.contentType
419
+ });
420
+ }
421
+ function isLikelyTranscodableAudio(params) {
422
+ const ext = normalizeLowercaseStringOrEmpty(path.extname(params.fileName));
423
+ const contentType = normalizeLowercaseStringOrEmpty(params.contentType);
424
+ return FEISHU_TRANSCODABLE_AUDIO_EXTS.has(ext) || mediaKindFromMime(contentType) === "audio";
425
+ }
426
+ async function transcodeToFeishuVoiceOpus(params) {
427
+ return await withTempWorkspace({
428
+ rootDir: resolvePreferredKlawTmpDir(),
429
+ prefix: "feishu-voice-"
430
+ }, async (workspace) => {
431
+ const ext = normalizeLowercaseStringOrEmpty(path.extname(params.fileName));
432
+ const inputExt = ext && ext.length <= 12 ? ext : ".audio";
433
+ const inputPath = await workspace.write(`input${inputExt}`, params.buffer);
434
+ await writeExternalFileWithinRoot({
435
+ rootDir: workspace.dir,
436
+ path: FEISHU_VOICE_FILE_NAME,
437
+ write: async (outputPath) => {
438
+ await runFfmpeg([
439
+ "-hide_banner",
440
+ "-loglevel",
441
+ "error",
442
+ "-y",
443
+ "-i",
444
+ inputPath,
445
+ "-vn",
446
+ "-sn",
447
+ "-dn",
448
+ "-t",
449
+ String(MEDIA_FFMPEG_MAX_AUDIO_DURATION_SECS),
450
+ "-ar",
451
+ String(FEISHU_VOICE_SAMPLE_RATE_HZ),
452
+ "-ac",
453
+ "1",
454
+ "-c:a",
455
+ "libopus",
456
+ "-b:a",
457
+ FEISHU_VOICE_BITRATE,
458
+ "-f",
459
+ "ogg",
460
+ outputPath
461
+ ]);
462
+ }
463
+ });
464
+ return {
465
+ buffer: await workspace.read(FEISHU_VOICE_FILE_NAME),
466
+ fileName: FEISHU_VOICE_FILE_NAME,
467
+ contentType: "audio/ogg"
468
+ };
469
+ });
470
+ }
471
+ async function prepareFeishuVoiceMedia(params) {
472
+ if (isFeishuNativeVoiceAudio(params)) return params;
473
+ if (params.audioAsVoice !== true || !isLikelyTranscodableAudio(params)) return params;
474
+ try {
475
+ return await transcodeToFeishuVoiceOpus(params);
476
+ } catch (err) {
477
+ console.warn(`[feishu] audioAsVoice transcode failed; sending ${params.fileName} as a file attachment:`, err);
478
+ return params;
479
+ }
480
+ }
481
+ /**
482
+ * Upload and send media (image or file) from URL, local path, or buffer.
483
+ * When mediaUrl is a local path, mediaLocalRoots (from core outbound context)
484
+ * must be passed so loadWebMedia allows the path (post CVE-2026-26321).
485
+ */
486
+ async function sendMediaFeishu(params) {
487
+ const { cfg, to, mediaUrl, mediaBuffer, fileName, replyToMessageId, replyInThread, accountId, mediaLocalRoots, audioAsVoice } = params;
488
+ const account = resolveFeishuRuntimeAccount({
489
+ cfg,
490
+ accountId
491
+ });
492
+ if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
493
+ const mediaMaxBytes = (account.config?.mediaMaxMb ?? 30) * 1024 * 1024;
494
+ let buffer;
495
+ let name;
496
+ let contentType;
497
+ if (mediaBuffer) {
498
+ buffer = mediaBuffer;
499
+ name = fileName ?? "file";
500
+ } else if (mediaUrl) {
501
+ const loaded = await getFeishuRuntime().media.loadWebMedia(mediaUrl, {
502
+ maxBytes: mediaMaxBytes,
503
+ optimizeImages: false,
504
+ localRoots: mediaLocalRoots?.length ? mediaLocalRoots : void 0
505
+ });
506
+ buffer = loaded.buffer;
507
+ name = fileName ?? loaded.fileName ?? "file";
508
+ contentType = loaded.contentType;
509
+ } else throw new Error("Either mediaUrl or mediaBuffer must be provided");
510
+ const prepared = await prepareFeishuVoiceMedia({
511
+ buffer,
512
+ fileName: name,
513
+ contentType,
514
+ audioAsVoice
515
+ });
516
+ buffer = prepared.buffer;
517
+ name = prepared.fileName;
518
+ contentType = prepared.contentType;
519
+ const routing = resolveFeishuOutboundMediaKind({
520
+ fileName: name,
521
+ contentType
522
+ });
523
+ const voiceIntentDegradedToFile = audioAsVoice === true && routing.msgType !== "audio";
524
+ if (routing.msgType === "image") {
525
+ const { imageKey } = await uploadImageFeishu({
526
+ cfg,
527
+ image: buffer,
528
+ accountId
529
+ });
530
+ return {
531
+ ...await sendImageFeishu({
532
+ cfg,
533
+ to,
534
+ imageKey,
535
+ replyToMessageId,
536
+ replyInThread,
537
+ accountId
538
+ }),
539
+ ...voiceIntentDegradedToFile ? { voiceIntentDegradedToFile: true } : {}
540
+ };
541
+ }
542
+ const { fileKey } = await uploadFileFeishu({
543
+ cfg,
544
+ file: buffer,
545
+ fileName: name,
546
+ fileType: routing.fileType ?? "stream",
547
+ accountId
548
+ });
549
+ return {
550
+ ...await sendFileFeishu({
551
+ cfg,
552
+ to,
553
+ fileKey,
554
+ msgType: routing.msgType,
555
+ replyToMessageId,
556
+ replyInThread,
557
+ accountId
558
+ }),
559
+ ...voiceIntentDegradedToFile ? { voiceIntentDegradedToFile: true } : {}
560
+ };
561
+ }
562
+ //#endregion
563
+ //#region extensions/feishu/src/types.ts
564
+ function isFeishuGroupChatType(chatType) {
565
+ return chatType === "group" || chatType === "topic_group";
566
+ }
567
+ //#endregion
568
+ //#region extensions/feishu/src/mention.ts
569
+ function isFeishuBroadcastMention(mention) {
570
+ const normalizedKey = mention.key?.trim().toLowerCase();
571
+ if (normalizedKey === "@all" || normalizedKey === "@_all") return true;
572
+ return [
573
+ mention.id?.open_id,
574
+ mention.id?.user_id,
575
+ mention.id?.union_id
576
+ ].some((id) => id?.trim().toLowerCase() === "all");
577
+ }
578
+ /**
579
+ * Extract mention targets from message event (excluding the bot itself)
580
+ */
581
+ function extractMentionTargets(event, botOpenId) {
582
+ return (event.message.mentions ?? []).filter((m) => {
583
+ if (isFeishuBroadcastMention(m)) return false;
584
+ if (botOpenId && m.id.open_id === botOpenId) return false;
585
+ return !!m.id.open_id;
586
+ }).map((m) => ({
587
+ openId: m.id.open_id,
588
+ name: m.name,
589
+ key: m.key
590
+ }));
591
+ }
592
+ /**
593
+ * Check if message is a mention forward request
594
+ * Rules:
595
+ * - Group: message mentions bot + at least one other user
596
+ * - DM: message mentions any user (no need to mention bot)
597
+ */
598
+ function isMentionForwardRequest(event, botOpenId) {
599
+ const mentions = event.message.mentions ?? [];
600
+ if (mentions.length === 0) return false;
601
+ const isDirectMessage = !isFeishuGroupChatType(event.message.chat_type);
602
+ const userMentions = mentions.filter((m) => !isFeishuBroadcastMention(m));
603
+ const hasOtherMention = userMentions.some((m) => m.id.open_id !== botOpenId);
604
+ if (isDirectMessage) return hasOtherMention;
605
+ return userMentions.some((m) => m.id.open_id === botOpenId) && hasOtherMention;
606
+ }
607
+ /**
608
+ * Format @mention for text message
609
+ */
610
+ function formatMentionForText(target) {
611
+ return `<at user_id="${target.openId}">${target.name}</at>`;
612
+ }
613
+ /**
614
+ * Format @mention for card message (lark_md)
615
+ */
616
+ function formatMentionForCard(target) {
617
+ return `<at id=${target.openId}></at>`;
618
+ }
619
+ /**
620
+ * Build complete message with @mentions (text format)
621
+ */
622
+ function buildMentionedMessage(targets, message) {
623
+ if (targets.length === 0) return message;
624
+ return `${targets.map((t) => formatMentionForText(t)).join(" ")} ${message}`;
625
+ }
626
+ /**
627
+ * Build card content with @mentions (Markdown format)
628
+ */
629
+ function buildMentionedCardContent(targets, message) {
630
+ if (targets.length === 0) return message;
631
+ return `${targets.map((t) => formatMentionForCard(t)).join(" ")} ${message}`;
632
+ }
633
+ //#endregion
634
+ //#region extensions/feishu/src/post.ts
635
+ const FALLBACK_POST_TEXT = "[Rich text message]";
636
+ const MARKDOWN_SPECIAL_CHARS = /([\\`*_{}[\]()#+\-!|>~])/g;
637
+ function toStringOrEmpty(value) {
638
+ return typeof value === "string" ? value : "";
639
+ }
640
+ function escapeMarkdownText(text) {
641
+ return text.replace(MARKDOWN_SPECIAL_CHARS, "\\$1");
642
+ }
643
+ function toBoolean(value) {
644
+ return value === true || value === 1 || value === "true";
645
+ }
646
+ function isStyleEnabled(style, key) {
647
+ if (!style) return false;
648
+ return toBoolean(style[key]);
649
+ }
650
+ function wrapInlineCode(text) {
651
+ const maxRun = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
652
+ const fence = "`".repeat(maxRun + 1);
653
+ return `${fence}${text.startsWith("`") || text.endsWith("`") ? ` ${text} ` : text}${fence}`;
654
+ }
655
+ function sanitizeFenceLanguage(language) {
656
+ return language.trim().replace(/[^A-Za-z0-9_+#.-]/g, "");
657
+ }
658
+ function renderTextElement(element) {
659
+ const text = toStringOrEmpty(element.text);
660
+ const style = isRecord$2(element.style) ? element.style : void 0;
661
+ if (isStyleEnabled(style, "code")) return wrapInlineCode(text);
662
+ let rendered = escapeMarkdownText(text);
663
+ if (!rendered) return "";
664
+ if (isStyleEnabled(style, "bold")) rendered = `**${rendered}**`;
665
+ if (isStyleEnabled(style, "italic")) rendered = `*${rendered}*`;
666
+ if (isStyleEnabled(style, "underline")) rendered = `<u>${rendered}</u>`;
667
+ if (isStyleEnabled(style, "strikethrough") || isStyleEnabled(style, "line_through") || isStyleEnabled(style, "lineThrough")) rendered = `~~${rendered}~~`;
668
+ return rendered;
669
+ }
670
+ function renderLinkElement(element) {
671
+ const href = toStringOrEmpty(element.href).trim();
672
+ const text = toStringOrEmpty(element.text) || href;
673
+ if (!text) return "";
674
+ if (!href) return escapeMarkdownText(text);
675
+ return `[${escapeMarkdownText(text)}](${href})`;
676
+ }
677
+ function renderMentionElement(element) {
678
+ const mention = toStringOrEmpty(element.user_name) || toStringOrEmpty(element.user_id) || toStringOrEmpty(element.open_id);
679
+ if (!mention) return "";
680
+ return `@${escapeMarkdownText(mention)}`;
681
+ }
682
+ function renderEmotionElement(element) {
683
+ return escapeMarkdownText(toStringOrEmpty(element.emoji) || toStringOrEmpty(element.text) || toStringOrEmpty(element.emoji_type));
684
+ }
685
+ function renderCodeBlockElement(element) {
686
+ const language = sanitizeFenceLanguage(toStringOrEmpty(element.language) || toStringOrEmpty(element.lang));
687
+ const code = (toStringOrEmpty(element.text) || toStringOrEmpty(element.content)).replace(/\r\n/g, "\n");
688
+ return `\`\`\`${language}\n${code}${code.endsWith("\n") ? "" : "\n"}\`\`\``;
689
+ }
690
+ function renderElement(element, imageKeys, mediaKeys, mentionedOpenIds) {
691
+ if (!isRecord$2(element)) return escapeMarkdownText(toStringOrEmpty(element));
692
+ switch (normalizeLowercaseStringOrEmpty(toStringOrEmpty(element.tag))) {
693
+ case "text": return renderTextElement(element);
694
+ case "a": return renderLinkElement(element);
695
+ case "at":
696
+ {
697
+ const normalizedMention = normalizeFeishuExternalKey(toStringOrEmpty(element.open_id) || toStringOrEmpty(element.user_id));
698
+ if (normalizedMention) mentionedOpenIds.push(normalizedMention);
699
+ }
700
+ return renderMentionElement(element);
701
+ case "img": {
702
+ const imageKey = normalizeFeishuExternalKey(toStringOrEmpty(element.image_key));
703
+ if (imageKey) imageKeys.push(imageKey);
704
+ return "![image]";
705
+ }
706
+ case "media": {
707
+ const fileKey = normalizeFeishuExternalKey(toStringOrEmpty(element.file_key));
708
+ if (fileKey) {
709
+ const fileName = toStringOrEmpty(element.file_name) || void 0;
710
+ mediaKeys.push({
711
+ fileKey,
712
+ fileName
713
+ });
714
+ }
715
+ return "[media]";
716
+ }
717
+ case "emotion": return renderEmotionElement(element);
718
+ case "md":
719
+ case "lark_md": return toStringOrEmpty(element.text) || toStringOrEmpty(element.content);
720
+ case "br": return "\n";
721
+ case "hr": return "\n\n---\n\n";
722
+ case "code": {
723
+ const code = toStringOrEmpty(element.text) || toStringOrEmpty(element.content);
724
+ return code ? wrapInlineCode(code) : "";
725
+ }
726
+ case "code_block":
727
+ case "pre": return renderCodeBlockElement(element);
728
+ default: return escapeMarkdownText(toStringOrEmpty(element.text));
729
+ }
730
+ }
731
+ function toPostPayload(candidate) {
732
+ if (!isRecord$2(candidate) || !Array.isArray(candidate.content)) return null;
733
+ return {
734
+ title: toStringOrEmpty(candidate.title),
735
+ content: candidate.content
736
+ };
737
+ }
738
+ function resolveLocalePayload(candidate) {
739
+ const direct = toPostPayload(candidate);
740
+ if (direct) return direct;
741
+ if (!isRecord$2(candidate)) return null;
742
+ for (const value of Object.values(candidate)) {
743
+ const localePayload = toPostPayload(value);
744
+ if (localePayload) return localePayload;
745
+ }
746
+ return null;
747
+ }
748
+ function resolvePostPayload(parsed) {
749
+ const direct = toPostPayload(parsed);
750
+ if (direct) return direct;
751
+ if (!isRecord$2(parsed)) return null;
752
+ const wrappedPost = resolveLocalePayload(parsed.post);
753
+ if (wrappedPost) return wrappedPost;
754
+ return resolveLocalePayload(parsed);
755
+ }
756
+ function parsePostContent(content) {
757
+ try {
758
+ const payload = resolvePostPayload(JSON.parse(content));
759
+ if (!payload) return {
760
+ textContent: FALLBACK_POST_TEXT,
761
+ imageKeys: [],
762
+ mediaKeys: [],
763
+ mentionedOpenIds: []
764
+ };
765
+ const imageKeys = [];
766
+ const mediaKeys = [];
767
+ const mentionedOpenIds = [];
768
+ const paragraphs = [];
769
+ for (const paragraph of payload.content) {
770
+ if (!Array.isArray(paragraph)) continue;
771
+ let renderedParagraph = "";
772
+ for (const element of paragraph) renderedParagraph += renderElement(element, imageKeys, mediaKeys, mentionedOpenIds);
773
+ paragraphs.push(renderedParagraph);
774
+ }
775
+ return {
776
+ textContent: [escapeMarkdownText(payload.title.trim()), paragraphs.join("\n").trim()].filter(Boolean).join("\n\n").trim() || FALLBACK_POST_TEXT,
777
+ imageKeys,
778
+ mediaKeys,
779
+ mentionedOpenIds
780
+ };
781
+ } catch {
782
+ return {
783
+ textContent: FALLBACK_POST_TEXT,
784
+ imageKeys: [],
785
+ mediaKeys: [],
786
+ mentionedOpenIds: []
787
+ };
788
+ }
789
+ }
790
+ //#endregion
791
+ //#region extensions/feishu/src/send.ts
792
+ const WITHDRAWN_REPLY_ERROR_CODES = new Set([230011, 231003]);
793
+ const INTERACTIVE_CARD_FALLBACK_TEXT = "[Interactive Card]";
794
+ const POST_FALLBACK_TEXT = "[Rich text message]";
795
+ const FEISHU_CARD_TEMPLATES = new Set([
796
+ "blue",
797
+ "green",
798
+ "red",
799
+ "orange",
800
+ "purple",
801
+ "indigo",
802
+ "wathet",
803
+ "turquoise",
804
+ "yellow",
805
+ "grey",
806
+ "carmine",
807
+ "violet",
808
+ "lime"
809
+ ]);
810
+ function shouldFallbackFromReplyTarget(response) {
811
+ if (response.code !== void 0 && WITHDRAWN_REPLY_ERROR_CODES.has(response.code)) return true;
812
+ const msg = normalizeLowercaseStringOrEmpty(response.msg);
813
+ return msg.includes("withdrawn") || msg.includes("not found");
814
+ }
815
+ /** Check whether a thrown error indicates a withdrawn/not-found reply target. */
816
+ function isWithdrawnReplyError(err) {
817
+ if (typeof err !== "object" || err === null) return false;
818
+ const code = err.code;
819
+ if (typeof code === "number" && WITHDRAWN_REPLY_ERROR_CODES.has(code)) return true;
820
+ const response = err.response;
821
+ if (typeof response?.data?.code === "number" && WITHDRAWN_REPLY_ERROR_CODES.has(response.data.code)) return true;
822
+ return false;
823
+ }
824
+ function isRecord$1(value) {
825
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
826
+ }
827
+ /** Send a direct message as a fallback when a reply target is unavailable. */
828
+ async function sendFallbackDirect(client, params, errorPrefix) {
829
+ const response = await requestFeishuApi(() => client.im.message.create({
830
+ params: { receive_id_type: params.receiveIdType },
831
+ data: {
832
+ receive_id: params.receiveId,
833
+ content: params.content,
834
+ msg_type: params.msgType
835
+ }
836
+ }), errorPrefix, { includeNestedErrorLogId: true });
837
+ assertFeishuMessageApiSuccess(response, errorPrefix);
838
+ return toFeishuSendResult(response, params.receiveId, resolveFeishuReceiptKind(params.msgType));
839
+ }
840
+ async function sendReplyOrFallbackDirect(client, params) {
841
+ if (!params.replyToMessageId) return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
842
+ const replyTargetFallbackError = params.replyInThread && params.allowTopLevelReplyFallback !== true ? /* @__PURE__ */ new Error("Feishu thread reply failed: reply target is unavailable and cannot safely fall back to a top-level send.") : null;
843
+ let response;
844
+ try {
845
+ response = await client.im.message.reply({
846
+ path: { message_id: params.replyToMessageId },
847
+ data: {
848
+ content: params.content,
849
+ msg_type: params.msgType,
850
+ ...params.replyInThread ? { reply_in_thread: true } : {}
851
+ }
852
+ });
853
+ } catch (err) {
854
+ if (!isWithdrawnReplyError(err)) throw createFeishuApiError(err, params.replyErrorPrefix, { includeNestedErrorLogId: true });
855
+ if (replyTargetFallbackError) throw replyTargetFallbackError;
856
+ return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
857
+ }
858
+ if (shouldFallbackFromReplyTarget(response)) {
859
+ if (replyTargetFallbackError) throw replyTargetFallbackError;
860
+ return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
861
+ }
862
+ assertFeishuMessageApiSuccess(response, params.replyErrorPrefix);
863
+ return toFeishuSendResult(response, params.directParams.receiveId, resolveFeishuReceiptKind(params.msgType));
864
+ }
865
+ function normalizeCardTemplateVariable(value) {
866
+ if (typeof value === "string") return value;
867
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
868
+ }
869
+ function readCardTemplateVariables(parsed) {
870
+ const variables = /* @__PURE__ */ new Map();
871
+ for (const source of [parsed.template_variable, parsed.template_variables]) {
872
+ if (!isRecord$1(source)) continue;
873
+ for (const [key, value] of Object.entries(source)) {
874
+ const normalized = normalizeCardTemplateVariable(value);
875
+ if (normalized !== void 0) variables.set(key, normalized);
876
+ }
877
+ }
878
+ return variables;
879
+ }
880
+ function applyCardTemplateVariables(text, variables) {
881
+ if (variables.size === 0) return text;
882
+ return text.replace(/\$\{([A-Za-z0-9_.-]+)\}|\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}/g, (match, a, b) => {
883
+ const variableName = typeof a === "string" ? a : b;
884
+ return variables.get(variableName) ?? match;
885
+ });
886
+ }
887
+ function extractInteractiveElementText(element, variables) {
888
+ if (!isRecord$1(element)) return;
889
+ const tag = typeof element.tag === "string" ? element.tag : "";
890
+ const text = isRecord$1(element.text) ? element.text : void 0;
891
+ if (tag === "div" && typeof text?.content === "string") return applyCardTemplateVariables(text.content, variables);
892
+ if ((tag === "markdown" || tag === "lark_md") && typeof element.content === "string") return applyCardTemplateVariables(element.content, variables);
893
+ if (tag === "plain_text" && typeof element.content === "string") return applyCardTemplateVariables(element.content, variables);
894
+ }
895
+ function extractInteractiveElementsText(elements, variables) {
896
+ const texts = [];
897
+ for (const element of elements) {
898
+ const text = extractInteractiveElementText(element, variables);
899
+ if (text !== void 0) texts.push(text);
900
+ }
901
+ return texts.join("\n").trim();
902
+ }
903
+ function readInteractiveElementArrays(parsed) {
904
+ const body = isRecord$1(parsed.body) ? parsed.body : void 0;
905
+ const elementArrays = [];
906
+ for (const candidate of [parsed.elements, body?.elements]) if (Array.isArray(candidate)) elementArrays.push(candidate);
907
+ for (const candidate of [parsed.i18n_elements, body?.i18n_elements]) {
908
+ if (!isRecord$1(candidate)) continue;
909
+ for (const localeElements of Object.values(candidate)) if (Array.isArray(localeElements)) elementArrays.push(localeElements);
910
+ }
911
+ return elementArrays;
912
+ }
913
+ function parseInteractivePostFallback(parsed) {
914
+ const textContent = parsePostContent(JSON.stringify(parsed)).textContent.trim();
915
+ return textContent && textContent !== POST_FALLBACK_TEXT ? textContent : void 0;
916
+ }
917
+ function parseInteractiveCardContent(parsed) {
918
+ if (!isRecord$1(parsed)) return INTERACTIVE_CARD_FALLBACK_TEXT;
919
+ const variables = readCardTemplateVariables(parsed);
920
+ for (const elements of readInteractiveElementArrays(parsed)) {
921
+ const text = extractInteractiveElementsText(elements, variables);
922
+ if (text) return text;
923
+ }
924
+ return parseInteractivePostFallback(parsed) ?? INTERACTIVE_CARD_FALLBACK_TEXT;
925
+ }
926
+ function parseFeishuMessageContent(rawContent, msgType) {
927
+ if (!rawContent) return "";
928
+ let parsed;
929
+ try {
930
+ parsed = JSON.parse(rawContent);
931
+ } catch {
932
+ return rawContent;
933
+ }
934
+ if (msgType === "text") {
935
+ const text = parsed?.text;
936
+ return typeof text === "string" ? text : "[Text message]";
937
+ }
938
+ if (msgType === "post") return parsePostContent(rawContent).textContent;
939
+ if (msgType === "interactive") return parseInteractiveCardContent(parsed);
940
+ if (typeof parsed === "string") return parsed;
941
+ const genericText = parsed?.text;
942
+ if (typeof genericText === "string" && genericText.trim()) return genericText;
943
+ const genericTitle = parsed?.title;
944
+ if (typeof genericTitle === "string" && genericTitle.trim()) return genericTitle;
945
+ return `[${msgType || "unknown"} message]`;
946
+ }
947
+ function parseFeishuMessageItem(item, fallbackMessageId) {
948
+ const msgType = item.msg_type ?? "text";
949
+ const rawContent = item.body?.content ?? "";
950
+ return {
951
+ messageId: item.message_id ?? fallbackMessageId ?? "",
952
+ chatId: item.chat_id ?? "",
953
+ chatType: item.chat_type === "group" || item.chat_type === "topic_group" || item.chat_type === "private" || item.chat_type === "p2p" ? item.chat_type : void 0,
954
+ senderId: item.sender?.id,
955
+ senderOpenId: item.sender?.id_type === "open_id" ? item.sender?.id : void 0,
956
+ senderType: item.sender?.sender_type,
957
+ content: parseFeishuMessageContent(rawContent, msgType),
958
+ contentType: msgType,
959
+ createTime: item.create_time ? Number.parseInt(item.create_time, 10) : void 0,
960
+ threadId: item.thread_id || void 0
961
+ };
962
+ }
963
+ /**
964
+ * Get a message by its ID.
965
+ * Useful for fetching quoted/replied message content.
966
+ */
967
+ async function getMessageFeishu(params) {
968
+ const { cfg, messageId, accountId } = params;
969
+ const account = resolveFeishuRuntimeAccount({
970
+ cfg,
971
+ accountId
972
+ });
973
+ if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
974
+ const client = createFeishuClient(account);
975
+ try {
976
+ const response = await client.im.message.get({ path: { message_id: messageId } });
977
+ if (response.code !== 0) return null;
978
+ const rawItem = response.data?.items?.[0] ?? response.data;
979
+ const item = rawItem && (rawItem.body !== void 0 || rawItem.message_id !== void 0) ? rawItem : null;
980
+ if (!item) return null;
981
+ return parseFeishuMessageItem(item, messageId);
982
+ } catch {
983
+ return null;
984
+ }
985
+ }
986
+ /**
987
+ * List messages in a Feishu thread (topic).
988
+ * Uses container_id_type=thread to directly query thread messages,
989
+ * which includes both the root message and all replies (including bot replies).
990
+ */
991
+ async function listFeishuThreadMessages(params) {
992
+ const { cfg, threadId, currentMessageId, rootMessageId, limit = 20, accountId } = params;
993
+ const account = resolveFeishuRuntimeAccount({
994
+ cfg,
995
+ accountId
996
+ });
997
+ if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
998
+ const response = await createFeishuClient(account).im.message.list({ params: {
999
+ container_id_type: "thread",
1000
+ container_id: threadId,
1001
+ sort_type: "ByCreateTimeDesc",
1002
+ page_size: Math.min(limit + 1, 50)
1003
+ } });
1004
+ if (response.code !== 0) throw new Error(`Feishu thread list failed: code=${response.code} msg=${response.msg ?? "unknown"}`);
1005
+ const items = response.data?.items ?? [];
1006
+ const results = [];
1007
+ for (const item of items) {
1008
+ if (currentMessageId && item.message_id === currentMessageId) continue;
1009
+ if (rootMessageId && item.message_id === rootMessageId) continue;
1010
+ const parsed = parseFeishuMessageItem(item);
1011
+ results.push({
1012
+ messageId: parsed.messageId,
1013
+ senderId: parsed.senderId,
1014
+ senderType: parsed.senderType,
1015
+ content: parsed.content,
1016
+ contentType: parsed.contentType,
1017
+ createTime: parsed.createTime
1018
+ });
1019
+ if (results.length >= limit) break;
1020
+ }
1021
+ results.reverse();
1022
+ return results;
1023
+ }
1024
+ function buildFeishuPostMessagePayload(params) {
1025
+ const { messageText } = params;
1026
+ return {
1027
+ content: JSON.stringify({ zh_cn: { content: [[{
1028
+ tag: "md",
1029
+ text: messageText
1030
+ }]] } }),
1031
+ msgType: "post"
1032
+ };
1033
+ }
1034
+ async function sendMessageFeishu(params) {
1035
+ const { cfg, to, text, replyToMessageId, replyInThread, allowTopLevelReplyFallback, mentions, accountId } = params;
1036
+ const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({
1037
+ cfg,
1038
+ to,
1039
+ accountId
1040
+ });
1041
+ const tableMode = resolveMarkdownTableMode({
1042
+ cfg,
1043
+ channel: "feishu"
1044
+ });
1045
+ let rawText = text ?? "";
1046
+ if (mentions && mentions.length > 0) rawText = buildMentionedMessage(mentions, rawText);
1047
+ const { content, msgType } = buildFeishuPostMessagePayload({ messageText: convertMarkdownTables(rawText, tableMode) });
1048
+ return sendReplyOrFallbackDirect(client, {
1049
+ replyToMessageId,
1050
+ replyInThread,
1051
+ allowTopLevelReplyFallback,
1052
+ content,
1053
+ msgType,
1054
+ directParams: {
1055
+ receiveId,
1056
+ receiveIdType,
1057
+ content,
1058
+ msgType
1059
+ },
1060
+ directErrorPrefix: "Feishu send failed",
1061
+ replyErrorPrefix: "Feishu reply failed"
1062
+ });
1063
+ }
1064
+ async function sendCardFeishu(params) {
1065
+ const { cfg, to, card, replyToMessageId, replyInThread, allowTopLevelReplyFallback, accountId } = params;
1066
+ const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({
1067
+ cfg,
1068
+ to,
1069
+ accountId
1070
+ });
1071
+ const content = JSON.stringify(card);
1072
+ return sendReplyOrFallbackDirect(client, {
1073
+ replyToMessageId,
1074
+ replyInThread,
1075
+ allowTopLevelReplyFallback,
1076
+ content,
1077
+ msgType: "interactive",
1078
+ directParams: {
1079
+ receiveId,
1080
+ receiveIdType,
1081
+ content,
1082
+ msgType: "interactive"
1083
+ },
1084
+ directErrorPrefix: "Feishu card send failed",
1085
+ replyErrorPrefix: "Feishu card reply failed"
1086
+ });
1087
+ }
1088
+ async function editMessageFeishu(params) {
1089
+ const { cfg, messageId, text, card, accountId } = params;
1090
+ const account = resolveFeishuRuntimeAccount({
1091
+ cfg,
1092
+ accountId
1093
+ });
1094
+ if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
1095
+ if ((typeof text === "string" && text.trim().length > 0) === Boolean(card)) throw new Error("Feishu edit requires exactly one of text or card.");
1096
+ const client = createFeishuClient(account);
1097
+ if (card) {
1098
+ const content = JSON.stringify(card);
1099
+ const response = await client.im.message.patch({
1100
+ path: { message_id: messageId },
1101
+ data: { content }
1102
+ });
1103
+ if (response.code !== 0) throw new Error(`Feishu message edit failed: ${response.msg || `code ${response.code}`}`);
1104
+ return {
1105
+ messageId,
1106
+ contentType: "interactive"
1107
+ };
1108
+ }
1109
+ const payload = buildFeishuPostMessagePayload({ messageText: convertMarkdownTables(text, resolveMarkdownTableMode({
1110
+ cfg,
1111
+ channel: "feishu"
1112
+ })) });
1113
+ const response = await client.im.message.patch({
1114
+ path: { message_id: messageId },
1115
+ data: { content: payload.content }
1116
+ });
1117
+ if (response.code !== 0) throw new Error(`Feishu message edit failed: ${response.msg || `code ${response.code}`}`);
1118
+ return {
1119
+ messageId,
1120
+ contentType: "post"
1121
+ };
1122
+ }
1123
+ /**
1124
+ * Build a Feishu interactive card with markdown content.
1125
+ * Cards render markdown properly (code blocks, tables, links, etc.)
1126
+ * Uses schema 2.0 format for proper markdown rendering.
1127
+ */
1128
+ function buildMarkdownCard(text) {
1129
+ return {
1130
+ schema: "2.0",
1131
+ config: { width_mode: "fill" },
1132
+ body: { elements: [{
1133
+ tag: "markdown",
1134
+ content: text
1135
+ }] }
1136
+ };
1137
+ }
1138
+ function resolveFeishuCardTemplate(template) {
1139
+ const normalized = normalizeOptionalLowercaseString(template);
1140
+ if (!normalized || !FEISHU_CARD_TEMPLATES.has(normalized)) return;
1141
+ return normalized;
1142
+ }
1143
+ /**
1144
+ * Build a Feishu interactive card with optional header and note footer.
1145
+ * When header/note are omitted, behaves identically to buildMarkdownCard.
1146
+ */
1147
+ function buildStructuredCard(text, options) {
1148
+ const elements = [{
1149
+ tag: "markdown",
1150
+ content: text
1151
+ }];
1152
+ if (options?.note) {
1153
+ elements.push({ tag: "hr" });
1154
+ elements.push({
1155
+ tag: "markdown",
1156
+ content: `<font color='grey'>${options.note}</font>`
1157
+ });
1158
+ }
1159
+ const card = {
1160
+ schema: "2.0",
1161
+ config: { width_mode: "fill" },
1162
+ body: { elements }
1163
+ };
1164
+ if (options?.header) card.header = {
1165
+ title: {
1166
+ tag: "plain_text",
1167
+ content: options.header.title
1168
+ },
1169
+ template: resolveFeishuCardTemplate(options.header.template) ?? "blue"
1170
+ };
1171
+ return card;
1172
+ }
1173
+ /**
1174
+ * Send a message as a structured card with optional header and note.
1175
+ */
1176
+ async function sendStructuredCardFeishu(params) {
1177
+ const { cfg, to, text, replyToMessageId, replyInThread, allowTopLevelReplyFallback, mentions, accountId, header, note } = params;
1178
+ let cardText = text;
1179
+ if (mentions && mentions.length > 0) cardText = buildMentionedCardContent(mentions, text);
1180
+ return sendCardFeishu({
1181
+ cfg,
1182
+ to,
1183
+ card: buildStructuredCard(cardText, {
1184
+ header,
1185
+ note
1186
+ }),
1187
+ replyToMessageId,
1188
+ replyInThread,
1189
+ allowTopLevelReplyFallback,
1190
+ accountId
1191
+ });
1192
+ }
1193
+ /**
1194
+ * Send a message as a markdown card (interactive message).
1195
+ * This renders markdown properly in Feishu (code blocks, tables, bold/italic, etc.)
1196
+ */
1197
+ async function sendMarkdownCardFeishu(params) {
1198
+ const { cfg, to, text, replyToMessageId, replyInThread, allowTopLevelReplyFallback, mentions, accountId } = params;
1199
+ let cardText = text;
1200
+ if (mentions && mentions.length > 0) cardText = buildMentionedCardContent(mentions, text);
1201
+ return sendCardFeishu({
1202
+ cfg,
1203
+ to,
1204
+ card: buildMarkdownCard(cardText),
1205
+ replyToMessageId,
1206
+ replyInThread,
1207
+ allowTopLevelReplyFallback,
1208
+ accountId
1209
+ });
1210
+ }
1211
+ //#endregion
1212
+ export { normalizeFeishuExternalKey as _, sendCardFeishu as a, sendStructuredCardFeishu as c, isFeishuBroadcastMention as d, isMentionForwardRequest as f, shouldSuppressFeishuTextForVoiceMedia as g, sendMediaFeishu as h, resolveFeishuCardTemplate as i, parsePostContent as l, saveMessageResourceFeishu as m, getMessageFeishu as n, sendMarkdownCardFeishu as o, isFeishuGroupChatType as p, listFeishuThreadMessages as r, sendMessageFeishu as s, editMessageFeishu as t, extractMentionTargets as u };