@openclaw/feishu 2026.7.2-beta.2 → 2026.7.2-beta.4

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