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